类的形式
class Student:
name = 'who'#类属性 静态变量被所有类对象共享
def __init__(self,age,city)::#构造函数 这里面的age和city就是每个类对象独有的参数
self.age = age
self.__city = city#加了两个下划线__表示私有变量
def fun(self):#实例方法
print('实例方法',self.age)
@classmethod
def eat(cls):#类方法
print('%s在吃饭',cls.name)#在类方法里不能用self 只能用cls
@staticmethod
def method():#这是一个静态方法
print('方法')
stu = Student()
实例方法 静态方法 类方法的区别
实例方法
def fun(self):#实例方法
必须含有self 在调用时会自动把stu类对象最为参数传入
类方法
@classmethod
def fun(cls):#类方法
必须含有cls 在调用时会自动把Student类作为参数传入
cls.num_inst可以获取这个类有多少个对象
静态方法
@staticmethod
def fun():#静态方法
没有参数
动态绑定属性和方法
class Student:
def __init__(self,name,age):
self.name = name#这些属性都是类对象拥有的
self.age = age
stu1 = Student('张三',1)
stu2 = Student('李四',2)
# 动态绑定属性
stu1.gender = '女'#这是stu1独有的 stu2没有
print(stu2.gender)#这样就会报错
# 动态绑定方法
def show():
print('动态绑定的方法')
stu1.show = show
stu1.show()
继承
__init__构造器
前面的__表示是私有
__init__ 第一个参数必须为self 后续参数自定义
class A:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
a = A(1,2,3)