11.2 定义类和对象独有的特征

11.2 定义类和对象独有的特征

1. 定义对象独有的特征(属性)

class OldBoyStudent: 
    school='oldboy'
    addr='shanghai'。
    def choose_course(self):
        print('is chosing course')

#创造对象的过程(实例化对象)
stu1=OldBoyStudent() 
stu2=OldBoyStudent() 
stu3=OldBoyStudent() 

#定制化对象独有特征
print(OldBoyStudent.__dict__) #{'__module__': '__main__', 'school': 'oldboy', 'addr': 'shanghai', 'choose_course': <function OldBoyStudent.choose_course at 0x00000198F32C2DE0>, '__dict__': <attribute '__dict__' of 'OldBoyStudent' objects>, '__weakref__': <attribute '__weakref__' of 'OldBoyStudent' objects>, '__doc__': None}
print('stu1',stu1.__dict__)  #stu1 {}

stu1.__dict__['id']=2222
print('stu1',stu1.__dict__)  #stu1 {'学号': 2222}
print(stu1.id) 
#这样添加麻烦

print('stu2',stu2.__dict__)  #stu2 {}
stu2.id=3333 #不影响类
print('stu2',stu2.__dict__)  #添加简单;stu2 {'id': 3333};对象stu2有id


print(OldBoyStudent.__dict__) #类OldBoyStudent没有id
class OldBoyStudent: 
    school='oldboy'
    count=0
    
    def choose_course(self):
        print('is chosing course')

stu1=OldBoyStudent() 
stu1.count+=1
print('stu1',stu1.count)
#输出
stu1 1

stu2=OldBoyStudent() 
stu2.count+=1
print('stu2',stu2.count)
#输出
stu2 1

stu3=OldBoyStudent() 
stu3.count+=1
print('stu3',stu3.count)
#输出
stu3 1

print('OldBoyStudent',OldBoyStudent.count)
#输出
OldBoyStudent 0

#各个对象的属性互不干扰
#既加id又加count加name加age

2. __init__ 构造函数

class OldBoyStudent: 
    school='oldboy'
    count=0
    
    def choose_course(self):
        print('is chosing course')
        
stu1=OldBoyStudent() 
stu1.id=1111
stu1.name='coco'
stu1.age=10
print(stu1.id,stu1.name,stu1.age) 

#输出
1111 coco 10

#上述较麻烦,引出通过函数添加对象属性
class OldBoyStudent: 
    school='oldboy'
    count=0
    def choose_course(self):
        print('is chosing course')
stu2=OldBoyStudent() 


def init(obj,id,name,age):
    obj.id=id
    obj.name=name
    obj.age=age
    print(obj.id,obj.name,obj.age)
    
init(stu2,2222,'mike',18)
#输出
2222 mike 18

#上述较麻烦,因此引出__init__。
class OldBoyStudent: 
    school='oldboy'
    count=0
    def __init__(self,id,name,age): #__init__初始化属性;self是实例化的对象自动传值
        self.id=id #stu3.id=id
        self.name=name #stu3.name=name
        self.age=age
        OldBoyStudent.count+=1 
    def choose_course(self):
        print('is chosing course')

stu3=OldBoyStudent('3333','jane',18)  #传参个数和__init__形参个数一样
print(stu3.id,stu3.name,stu3.age)
#输出
3333 jane 18

stu4=OldBoyStudent('4444','tan',19) #每次实例化对象的时候都会自动调用__init__方法
print(stu4.id,stu4.name,stu4.age)
#输出
4444 tan 19

print(OldBoyStudent.count) 
#输出
2
posted @ 2025-09-08 18:38  bokebanla  阅读(9)  评论(0)    收藏  举报