#python-grammar #class
Class在__init__内和__init__外定义变量的区别
- 变量定义在__init__之外, 该变量隶属于这个类.
- 变量定义在__init__之内, 该变量隶属于这个实例对象.
示例:
class Book(object):
count = 100
def __init__(self, id, name):
self.book_id = id
self.book_name = name
def __add__(self, other):
return self.count + other.count
def show_info(self):
return (self.book_id, self.book_name, self.count)
b1 = Book(1, "b1")
b2 = Book(2, "b2")
sales_cnt = b1 + b2
print(sales_cnt)
count变量:不需要实例化就可以定义
Book.count = 200 # 不实例化改变count的初始变量,将改变全局所有实例的该默认取值
b1.count = 300 # 实例化改变b1这个示例的取值
id和name变量:只能且必须通过实例化进行定义,不得为空
b1 = Book(1, "b1")
b2 = Book(2, "b2")
b1.id = 3 # 只能通过实例化改变b1这个示例的取值
Marks:
-
同一个参数不同实例的数值类型可以不同
b1 = Book(1, "b1") b2 = Book("EJ038", "b2") b1.show_info() >(1, 'b1', 100) b2.show_info() >('EJ038', 'b2', 100)
关于class的属性
- delattr(), 从class的定义中删除某个属性
- hasattr(),判断class中是否含有某个属性
- getattr(),获取某个示例的某个属性值
- isinstance(), 判断是否含有这个class的实例
class Student():
def __init__(self,id=None,name=None):
self.id = id
self.name = name
xiaoming = Student(1,'xiaoming')
delattr(xiaoming,'id')
xiaoming.id
> AttributeError: 'Student' object has no attribute 'id'
hasattr(xiaoming,'id') # xiaoming 上没有 id 属性
> False
getsttr(xiaoming, "name")
> 'xiaoming'
isinstance(xiaoming,Student)
> True
装饰器
案例
# 不加装饰器
class Student:
def __init__(self):
self._name = None
def get_name(self):
return self._name
def set_name(self, val):
self._name = val
def del_name(self):
del self._name
name = property(get_name, set_name, del_name, "name property")
# 加装饰器
class Stu(object):
def __init__(self):
self._name = None
@property
def name(self):
return self._name
@name.setter
def name(self, val):
self._name = val
@name.deleter
def name(self):
del self._name
# 测试
xiaoming = Student()
xiaoming.name = 'xiaoming'
xiaoming.name
> 'xiaoming'
关于class的函数
- super(),调用父类class的属性
class Parent():
def __init__(self,x):
self.v = x
def add(self,x):
return self.v + x
class Son(Parent):
def add(self,y):
r = super().add(y) #直接调用父类的add方法
print(r) #子类的add与父类相比,能实现对结果的打印功能
Son(1).add(2)
> 3
- callable(),判断对象是否可被调用
class Stu2():
def __init__(self,id,name):
self.id = id
self.name = name
def __call__(self):
print('I can be called')
print(f'my name is {self.name}')
class stu3():
def __init__(self, id, name):
self.id = id
self.name = name
a = Stu2(100, "大宝")
b = stu3(200, "大毛")
print(a())
> I can be called
> my name is 大宝
print(b())
> TypeError: 'stu3' object is not callable