文章内容:
1、构造函数的作用
2、实例化
3、类变量与实例变量
4、类变量的意义
###构造函数的作用:能够让你的模板生成不同的对象
class Student():
name=''
age=0
def __init__(self):#########构造函数
print('student')
def do_homework(self):
print('homework')
student1=Student()#student,实例化
student1.__init__()#student,显示调用,其实实例化的时候已经调用了
class Student():
name=''
age=0
def __init__(self):
print('student')
return None
def do_homework(self):
print('homework')
student1=Student()#student
a=student1.__init__()#student
print(a)#None
print(type(a))#<class 'NoneType'>
class Student():
name=''
age=0
def __init__(self):
print('student')
return 'stu'
def do_homework(self):
print('homework')
student1=Student()#TypeError: __init__() should return None, not 'str'
#类变量和实例变量
#对象是由类这个模板创建出来的
class Student():
name=''
age=0
def __init__(self,name,age):
name=name#初始化对象的属性
age=age
def do_homework(self):
print('homework')
student1=Student('小红帽',9)
student2=Student('大红帽',18)
class Student():
name='name'
age=0
def __init__(self,name,age):#self名字可以替换成其它,并非关键字
self.name=name#和对象相关的实例变量
self.age=age
def do_homework(self):
print('homework')
student1=Student('小红帽',9)
student2=Student('大红帽',18)
print(student1.name)#小红帽
print(student2.name)#大红帽
print(Student.name)#name,这就是类变量和实例变量的区别
class Student():
name='xia'#类变量
age=0
def __init__(self,name,age):#构造函数
name=name#构造函数里面的变量,实例变量/对象
age=age
def do_homework(self):
print('homework')
student1=Student('小红帽',9)
print(student1.name)#xia,为什么???,类与对象的变量查找循序
print(Student.name)#xia
print(student1.__dict__)#{}
#修改
class Student():
name='xia'#类变量
age=0
def __init__(self,name,age):#构造函数
self.name=name#构造函数里面的变量,实例变量/对象
self.age=age
def do_homework(self):
print('homework')
student1=Student('小红帽',9)
print(student1.name)#小红帽
print(Student.name)#xia
print(student1.__dict__)#{'name': '小红帽', 'age': 9}
print(Student.__dict__)#(见下)和类相关的变量
'''
{'__module__': '__main__', 'name': 'xia', 'age': 0,
'__init__': <function Student.__init__ at
0x000000000BB78378>, 'do_homework': <function
Student.do_homework at 0x000000000BB78400>, '__dict__':
<attribute '__dict__' of 'Student' objects>, '__weakref__':
<attribute '__weakref__' of 'Student' objects>, '__doc__': None}
'''
class Student():
sum1=0#类变量的意义,不可能放在实例变量里
def __init__(self,name,age):
self.name=name
self.age=age
def do_homework(self):
print('homework')
student1=Student('小红帽',9)
print(student1.name)#小红帽
class Student():
name='xia'
age=0
def __init__(self,name,age):
self.name=name
self.age=age
print(name)#会出现什么?
print(age)#会出现什么?
def do_homework(self):
print('homework')
student1=Student('小红帽',9)#小红帽 9,出现这个
print(student1.name)#小红帽
print(Student.name)#xia