我真的是python和OOP的新手,只是想让事情变得更简单。但这我不是很了解。我有一个简单的类,但是运行此类时,我得到'Person'对象没有属性'first'。所以我在这里读到这是由于._(私有变量)引起的。我可以以某种方式访问它们吗?如果然后删除._并具有公共类(我想),我将得到此'str'对象不可调用。因此,如果我没看错,我正在用字符串覆盖一个函数,那是在声明p1和p2的地方发生的吗?我该如何解决?
class Person:
def __init__(self, **kwargs):
self._first = kwargs['first']
self._last = kwargs['last']
self._age = kwargs['age']
def first(self):
return self._first
def last(self):
return self._last
def age(self):
return self._age
def printPerson(o):
print('The persons name is {0} {1} and the age is
{2}.'.format(o.first(), o.last(), o.age()))
def main():
p1 = Person(first='John', last='Stevenson', age=35)
p2 = Person(first='Ash', last='Bradley', age=35)
printPerson(p1)
printPerson(p2)
if __name__ == '__main__': main()
答案 0 :(得分:1)
您可以这样做吗?
class Person:
def __init__(self, dictionary):
self._first = dictionary['first']
self._last = dictionary['last']
self._age = dictionary['age']
def first(self):
return self._first
def last(self):
return self._last
def age(self):
return self._age
def printPerson(o):
print('The persons name is {0} {1} and the age is {2}.'.format(o.first(), o.last(), o.age()))
def main():
p1 = Person({'first': 'John', 'last': 'Stevenson', 'age': 35})
p2 = Person({'first': 'Ash', 'last': 'Bradley', 'age': 35})
printPerson(p1)
printPerson(p2)
if __name__ == '__main__': main()
这首先解决了您在类的first,last和age方法上遇到的缩进问题。这可能不是您正在寻找的确切解决方案,但是我实现了一个字典,该字典在创建类的新实例时传递给该类,以便使用键['first']
,{ {1}}和['last']
。另外,您实际上并不需要在类中使用first,last或age方法……
['age']
同样可以工作,而且我认为您要完成的工作要清楚得多。您还可以将类所需的参数定义为类的一部分,并在情况下使用默认值
class Person:
def __init__(self, dictionary):
self._first = dictionary['first']
self._last = dictionary['last']
self._age = dictionary['age']
def printPerson(self):
print('The persons name is {0} {1} and the age is {2}.'.format(self._first, self._last, self._age))
def main():
p1 = Person({'first': 'John', 'last': 'Stevenson', 'age': 35})
p2 = Person({'first': 'Ash', 'last': 'Bradley', 'age': 35})
p1.printPerson()
p2.printPerson()
if __name__ == '__main__':
main()
使用此方法,您可以看到姓氏默认为'Doe',年龄默认为10。如所示,您可以像使用class Person:
def __init__(self, first, last='Doe', age=10):
self._first = first
self._last = last
self._age = age
def printPerson(self):
print('The persons name is {0} {1} and the age is {2}.'.format(self._first, self._last, self._age))
def main():
p1 = Person('John', 'Stevenson', 35)
p2 = Person('Ash', last='Bradley', age=35)
p1.printPerson()
p2.printPerson()
if __name__ == '__main__':
main()
那样从语法中指定这些参数,或者仅省略{ {1}}和Python将根据初始化实例时赋予该类的顺序来确定它们的位置