class Student:# 类的定义体
classroom = '101'# 类变量
address = 'beijing'
def __init__(self, name, age):
self.name = name
self.age = age
def print_age(self):
""" 定义实例方法,至少有一个self参数 """
print( '%s: %s'% (self.name, self.age))
@classmethod
def class_func(cls):
""" 定义类方法,至少有一个cls参数 """
print( '类方法')
@staticmethod
def static_func():
""" 定义静态方法 ,无默认参数"""
print( '静态方法')
class Foo(object):
""" 类三种方法语法形式"""
def instance_method(self):
print("是类{}的实例方法,只能被实例对象调用".format(Foo))
@staticmethod
def static_method(): # 静态方法,既不访问成员变量,也不访问类变量
print("是静态方法")
@classmethod
def class_method(cls):
print("是类方法")
foo = Foo()
foo.instance_method() # 使用实例调用实例方法
foo.static_method() # 使用实例调用静态方法
foo.class_method() # 使用实例调用类方法
print('----------------')
Foo.static_method() # 使用类直接调用静态方法
Foo.class_method() # 使用类直接调用类方法
Foo.instance_method(foo) # 如果使用类直接调用实例方法,需要显式地将实例作为参数传入
是类<class '__main__.Foo'>的实例方法,只能被实例对象调用
是静态方法
是类方法
----------------
是静态方法
是类方法
是类<class '__main__.Foo'>的实例方法,只能被实例对象调用
实例方法或者叫对象方法,指的是我们在类中定义的普通方法。
只有实例化对象之后才可以使用的方法,该方法的第一个形参self接收的一定是对象本身,实例方法可以访问实例属性。
class Car(object): # 类对象 ;当类加载时就分派内存空间,可用locals()查看
car_num = 0 # 类属性,在__init__外部定义。
def __init__(self, brand, price):
self.brand = brand # 实例属性,在__init__内部定义
self.price = price
Car.car_num += 1
def level(self): # 实例方法,调用了实例属性
if self.price > 300000:
print(f"{self.brand}是高级轿车")
else:
print(f"{self.brand}是非高级轿车")
@classmethod
def car_count(cls): # 类方法,只访问类变量
print(f"我有{cls.car_num}辆车")
@staticmethod
def tips(): # 静态方法,既不访问成员变量,也不访问类变量
print("温馨提示:开车不喝酒")
if __name__ == "__main__":
bmw = Car("宝马", 200000) # 通过类创建的对象称为实例对象
bmw.level() # 使用实例调用实例方法
wlhg = Car("五菱宏光", 400000)
wlhg.level() # 使用实例调用实例方法
Car.car_count() # 调用类方法
Car.tips() # 调用静态方法
宝马是非高级轿车
五菱宏光是高级轿车
我有2辆车
温馨提示:开车不喝酒
(1).格式:在方法上面添加 @staticmethod;@staticmethod称作装饰器
(2).参数:静态方法可以有参数也可以无参数
(3).应用场景:一般用于和类对象以及实例对象无关的代码。
(4).使用方式: 类名.类方法名(或者对象名.类方法名)。如字符串方法:"".maketrans('abc','123') 和 str.maketrans('abc','123')
注意:静态方法中无法调用任何类和对象的属性和方法,类静态方法与类的关系不大。定义静态方法主要是规避两个模块调用同名函数的情况。
无需实例化,可以通过类直接调用的方法,但是方法的第一个参数cls接收的一定是类本身
(1).在方法上面添加装饰器@classmethod
(2).方法的参数为 cls 也可以是其他名称,但是一般默认为cls
(3).cls 指向 类对象;Python 会自动将类本身绑定到cls参数
(5).应用场景:当一个方法中只涉及到类属性的时候可以使用类方法(类方法用来修改类属性)。
(5).使用: 可以是 对象名.类方法名。或者是 类名.类方法名
类的基础方法:
序号 | 目的 | 所编写代码 | Python 实际调用 |
---|---|---|---|
① | 初始化一个实例 | x = MyClass() |
x.__init__() |
② | 字符串的“官方”表现形式 | repr(x) |
x.__repr__() |
③ | 字符串的“非正式”值 | str(x) |
x.__str__() |
④ | 字节数组的“非正式”值 | bytes(x) |
x.__bytes__() |
⑤ | 格式化字符串的值 | format(x, format_spec) |
x.__format__(format_spec) |
魔法方法 |
含义 |
基本的魔法方法 |
|
__new__(cls[, ...]) |
1. __new__ 是在一个对象实例化的时候所调用的第一个方法 |
__init__(self[, ...]) |
构造器,当一个实例被创建的时候调用的初始化方法 |
__del__(self) |
析构器,当一个实例被销毁的时候调用的方法 |
__call__(self[, args...]) |
允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b) |
__len__(self) |
定义当被 len() 调用时的行为 |
__repr__(self) |
定义当被 repr() 调用时的行为 |
__str__(self) |
定义当被 str() 调用时的行为 |
__bytes__(self) |
定义当被 bytes() 调用时的行为 |
__hash__(self) |
定义当被 hash() 调用时的行为 |
__bool__(self) |
定义当被 bool() 调用时的行为,应该返回 True 或 False |
__format__(self, format_spec) |
定义当被 format() 调用时的行为 |
有关属性 |
|
__getattr__(self, name) |
定义当用户试图获取一个不存在的属性时的行为 |
__getattribute__(self, name) |
定义当该类的属性被访问时的行为 |
__setattr__(self, name, value) |
定义当一个属性被设置时的行为 |
__delattr__(self, name) |
定义当一个属性被删除时的行为 |
__dir__(self) |
定义当 dir() 被调用时的行为 |
__get__(self, instance, owner) |
定义当描述符的值被取得时的行为 |
__set__(self, instance, value) |
定义当描述符的值被改变时的行为 |
__delete__(self, instance) |
定义当描述符的值被删除时的行为 |
比较操作符 |
|
__lt__(self, other) |
定义小于号的行为:x < y 调用 x.__lt__(y) |
__le__(self, other) |
定义小于等于号的行为:x <= y 调用 x.__le__(y) |
__eq__(self, other) |
定义等于号的行为:x == y 调用 x.__eq__(y) |
__ne__(self, other) |
定义不等号的行为:x != y 调用 x.__ne__(y) |
__gt__(self, other) |
定义大于号的行为:x > y 调用 x.__gt__(y) |
__ge__(self, other) |
定义大于等于号的行为:x >= y 调用 x.__ge__(y) |
算数运算符 |
|
__add__(self, other) |
定义加法的行为:+ |
__sub__(self, other) |
定义减法的行为:- |
__mul__(self, other) |
定义乘法的行为:* |
__truediv__(self, other) |
定义真除法的行为:/ |
__floordiv__(self, other) |
定义整数除法的行为:// |
__mod__(self, other) |
定义取模算法的行为:% |
__divmod__(self, other) |
定义当被 divmod() 调用时的行为 |
__pow__(self, other[, modulo]) |
定义当被 power() 调用或 ** 运算时的行为 |
__lshift__(self, other) |
定义按位左移位的行为:<< |
__rshift__(self, other) |
定义按位右移位的行为:>> |
__and__(self, other) |
定义按位与操作的行为:& |
__xor__(self, other) |
定义按位异或操作的行为:^ |
__or__(self, other) |
定义按位或操作的行为:| |
反运算 |
|
__radd__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rsub__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rmul__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rtruediv__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rfloordiv__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rmod__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rdivmod__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rpow__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rlshift__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rrshift__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rand__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__rxor__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
__ror__(self, other) |
(与上方相同,当左操作数不支持相应的操作时被调用) |
增量赋值运算 |
|
__iadd__(self, other) |
定义赋值加法的行为:+= |
__isub__(self, other) |
定义赋值减法的行为:-= |
__imul__(self, other) |
定义赋值乘法的行为:*= |
__itruediv__(self, other) |
定义赋值真除法的行为:/= |
__ifloordiv__(self, other) |
定义赋值整数除法的行为://= |
__imod__(self, other) |
定义赋值取模算法的行为:%= |
__ipow__(self, other[, modulo]) |
定义赋值幂运算的行为:**= |
__ilshift__(self, other) |
定义赋值按位左移位的行为:<<= |
__irshift__(self, other) |
定义赋值按位右移位的行为:>>= |
__iand__(self, other) |
定义赋值按位与操作的行为:&= |
__ixor__(self, other) |
定义赋值按位异或操作的行为:^= |
__ior__(self, other) |
定义赋值按位或操作的行为:|= |
一元操作符 |
|
__pos__(self) |
定义正号的行为:+x |
__neg__(self) |
定义负号的行为:-x |
__abs__(self) |
定义当被 abs() 调用时的行为 |
__invert__(self) |
定义按位求反的行为:~x |
类型转换 |
|
__complex__(self) |
定义当被 complex() 调用时的行为(需要返回恰当的值) |
__int__(self) |
定义当被 int() 调用时的行为(需要返回恰当的值) |
__float__(self) |
定义当被 float() 调用时的行为(需要返回恰当的值) |
__round__(self[, n]) |
定义当被 round() 调用时的行为(需要返回恰当的值) |
__index__(self) |
1. 当对象是被应用在切片表达式中时,实现整形强制转换 |
上下文管理(with 语句) |
|
__enter__(self) |
1. 定义当使用 with 语句时的初始化行为 |
__exit__(self, exc_type, exc_value, traceback) |
1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么 |
容器类型 |
|
__len__(self) |
定义当被 len() 调用时的行为(返回容器中元素的个数) |
__getitem__(self, key) |
定义获取容器中指定元素的行为,相当于 self[key] |
__setitem__(self, key, value) |
定义设置容器中指定元素的行为,相当于 self[key] = value |
__delitem__(self, key) |
定义删除容器中指定元素的行为,相当于 del self[key] |
__iter__(self) |
定义当迭代容器中的元素的行为 |
__reversed__(self) |
定义当被 reversed() 调用时的行为 |
__contains__(self, item) |
定义当使用成员测试运算符(in 或 not in)时的行为 |
class average(object):
def __init__(self, *args):
self.args=args
self.count = 0
self.add = 0
for x in args:
self.count += 1
self.add += x
def __str__(self):
return '%s 个参数的和是: %s' %(self.count, self.add)
__repr__ = __str__
def __call__(self):
return self.add/self.count
def __len__(self):
return len(self.args)
s = average(10, 9, 8, 7)
print(len(s)) # 4 ; 调用 __len__ 方法
print(callable(s)) # True ; 因为实现了 __call__ 方法
print(s) # 4 个参数的和是: 34 ;调用 __str__ 方
# 当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
4
True
4 个参数的和是: 34