以下是我不理解的课程:
class Person():
def __init__(self,name,age):
self.name = name
self.age = age
def introduceSelf(self):
print("Hi, My name is" + self.name +"and i am " + self.age + "years old")
class Police(Person):
def arrest(self, toArrest):
print("you are arrested," + toArrest)
Jenny = Police("Jenny",20)
Micheal = Person("Micheal",72)
Jenny.arrest("Micheal")
__init__
方法中有两个参数,我必须定义变量
分别为self.name = name
和self.age = age
。
但是在arrest
方法中,即使我没有提到self.
,它仍然有效。
据我了解,我认为我必须用self.
连接方法中的任何变量(或参数)。我误会了什么?
答案 0 :(得分:0)
但是在逮捕方法中,即使我没有提到自我,它仍然有效。
是的,实例在 arrest 中未使用,因此它可以是静态方法,无论如何,不是必须要在非静态方法中使用实例
但是,如果您想表明逮捕谁,您将使用 self :
def arrest(self, toArrest):
print(self.name + " arrests " + toArrest)
我们可以假设 toArrest 也是 Person 吗?在这种情况下:
def arrest(self, toArrest):
print(self.name + " arrests " + toArrest.name)