pythonbook/Python高级编程/构造和初始化.py

19 lines
614 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Student(object):
def __new__(cls,*args,**kwargs):
print('我是new函数') #这是为了追踪new的执行过程
print(type(cls)) #这是为了追踪new的执行过程
return object.__new__(cls) #调用父类的object的new方法返回一个Student实例这个实例传递给init的self参数
def __init__(self,name,age):
self.name=name
self.age=age
print('我是init')
def study(self):
print('我爱学习!')
if __name__=='__main__':
s=Student('张三',25)
print(s.name)
print(s.age)
s.study()