파이썬을 배우기 위해 미니 게임을 작성하고 있습니다. 내 main.py 파일로 가져올 수있는 무기 클래스를 만들었습니다. 여기클래스 메서드가 파이썬 2.7.1에서 잘못된 숫자를 반환합니다.
class weapon(object):
def __init__(self, name):
self.weaponName = name
def weaponStrength(self, level, strength):
self.weaponLevel = level
self.weaponStrength = strength
damage = self.weaponStrength * level
print "Damage is equal to %r" % damage
return damage
는 무기 클래스를 사용하여 생성 된 개체 : 여기에
내가 만든 클래스입니다.# Creates an Object called sword using the weaponsClass
sword = weapon("sword")
# Calls a method of the weaponsClass to calculate weapon Strength. Returns a int
sword.weaponStrength(3, 20)
# Creates an Object called Magic Staff using the weaponsClass
magicStaff = weapon("Magic Staff")
# Calls a method of the weaponsClass to calculate weapon Strength. Returns a int
magicStaff.weaponStrength(5, 30)
# Sets a variable
swordStrength = sword.weaponStrength
# Sets a variable
magicStaffStrength = magicStaff.weaponStrength
# Prints the variable
print swordStrength
# Prints the variable
print magicStaffStrength
은 내가 swordStrength 및 magicStaffStrength이 메서드에 전달 된 강도 값과 같은 이유를 알아 내기 위해 노력하고있어.
도움을 주시면 감사하겠습니다.
감사합니다.
에 측면 메모를하는 방법을 분할 좋을 것 경우
weaponStrength
분명히 이름의 끔찍한 선택 : 그것보다 유지 보수 및 weaponStrength() 함수에서 별도의 부작용을 제거합니다. 즉, weaponStrength()는 반환되는 것과 같이 damage()와 같은 것으로 이름을 변경해야하며 인쇄 기능을 모두 제거해야합니다. 이렇게하면 self.weaponStrength 속성이 self.weaponStrength() 함수와 동일한 이름을 갖습니다. – hexparrot구조체를 생각해 보면 강도와 레벨을 설정하는'set_characteristics' 함수와 손상을 가져 오는'get_damage' 함수가 있다는 것을 의미합니다. 또는 특성을 설정 한 후에 변경하려고하지 않는 경우'set_characteristics' 호출에서 설정되는 직선의 멤버 변수를 가질 수 있습니다. –
@hexparrot swordStrength 변수를 설정할 때 잘못 되었기 때문에 값을보기 위해 print 함수를 거기에 넣었습니다. 나는 그것을 제거하고 sr2222에 의해 언급 된 변경을 할 것입니다. 귀하의 의견에 감사드립니다. – TDNS