类的定义
## 类名驼峰命名
## 类体中可以写任意Python代码,类体代码在定义时就运行
## __dic__ 可以查看类的命名空间
'''
{'__module__': '__main__', 'school': 'NUDT', 'adress': 'changsha', 'local': <classmethod(<function Student.local at 0x000001BCF418E9E0>)>, 'say_hello': <staticmethod(<function Student.say_hello at 0x000001BCF418EA70>)>, '__init__': <function Student.__init__ at 0x000001BCF418EB00>, 'say_score': <function Student.say_score at 0x000001BCF418EB90>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
'''
class Student:
# 类属性
# 可以被所有的实例对象所共享
school = 'NUDT'
adress = 'changsha'
stu_count = 0 # 统计注册的实例个数
# 类方法
@classmethod
def local(cls):
print(cls.adress)
# 静态方法
# 可以调用类的属性和方法
@staticmethod
def say_hello(str):
print(str)
Student.local()
# 通过构造函数__init__创建对象的属性
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
Student.stu_count += 1
# 创建实例对象方法
def say_score(self):
print(f'{self.name}的分数是{self.score}')
print(Student.say_score) ## <function Student.say_score at 0x00000255F6DDEB90>
s1 = Student('yanchen',18,80) ## 实例化
Student.say_score(s1) ## yanchen的分数是80
s1.say_score() ----- ## 本质是 Student.say_score(s1)
## 通过类名可以调用实例方法,需要传递实例进去
## 实例化发生的三件事情
1,先产生一个空对象
2,Python会自动调用 __init__方法
3,返回初始化完的对象
print(s1.__dict__) ------ ## ## {'name': 'yanchen', 'age': 18, 'score': 80}
No Comments