我寫了下面的python代碼,並嘗試使用__main__
來初始化兩個類對象,但運行python classPerson.py
時出現以下錯誤。我想知道在python中初始化類對象的正確方法是什麼。Python:是執行的入口點(__main__)?
Person(object):
def __init__(self, name, salary):
self.name = name
self.salary = salary
def getName():
return self.name
def getSalary():
return self.salary
if __name__ == '__main__':
bob = Person('Bob Smith', 40000)
sue = Person('Sue Funk', 35000)
print 'bob makes a salary of %d' % (bob.getSalary)
print 'sue's full name is %s' % (sue.getName)
錯誤:
Traceback (most recent call last):
File "classTest1.py", line 1, in <module>
class Person(object):
File "classTest1.py", line 14, in Person
bob = Person('Bob Smith', 40000)
NameError: name 'Person' is not defined
你的代碼是無效的,因爲貼了,因爲最後一個字符串將不編譯(單引號括起來的值與非轉義的單引號中它)。 –