一、__init__(self):构造器
class Bird:
def __init__(self, name): #构造函数,在类实例化之后,自动执行
self.hungry = 0 #饥饿程度
self.name = name
def sing(self):
self.hungry += 30
self.pd()
def eat(self):
self.hungry -= 30
self.pd()
def pd(self):
if self.hungry > 50:
print("%s 饿了需要喂食"%self.name)
else:
print("%s 饿了,但不想吃东西"%self.name)
b = Bird("Tom")
b.sing()
b.sing()
print(b.hungry)
在__init__时,有一个小细节需要注意
class Bird:
def __init__(self):
return # init可以return,但是不可以有值
b = Bird()
print(b)
可以return,但是不可以有值
二、__del__(self) —— 析构器
class Bird:
def __init__(self):
print("这是构造函数")
def __del__(self): #在实例被回收的时候执行
print("这是析构函数")
b = Bird()
del b
析构器主要是用于释放内存
三、
class Bird:
def __init__(self,name):
self.name = name
def __str__(self):
return self.name #打印输出的内容(显示为字符串),但仍然是实例
b = Bird("老鹰")
print(b)
print(type(b))
b1 = Bird("孔雀")
print(b1)
print(type(b1))
python 在打印一个实例化对象时,打印的是对象的地址,比如:<__main__.Workers object at 0x00000000255A9AC8>
而__str__(self)就可以打印具体的属性