类和对象

类和对象

1. 类和对象

2. 方法

2.1 实例方法

2.2 类方法和静态方法

类方法由@classmethod修饰,可以通过类/对象直接调用,并且会自动绑定第一个参数(cls)。
静态方法由@staticmethod修饰,可以通过类/对象直接调用,但是不会主动绑定cls

2.4 @函数修饰器

当@A修饰B时,函数修饰器的工作流程如下:

  1. 将被修饰的函数B作为参数传递给修饰函数A。
  2. 将函数B修饰为第1步的返回值。
def funcA(fn):  
    print("A")  
    fn()  
    return 'fkit'  
  
@funcA  
def funcB():  
    print("B")  
print(funcB)
A
B
fkit

2.5 成员变量

1. 类变量和实例变量

类变量不论是在全局空间还是类空间中都需要通过类名来调用。
实例变量是在实例方法中申请的变量。

2. property函数定义属性

3. 隐藏和封装

类似于private ,但是Python并没有真正的实现对类空间中方法和变量的隐藏,只是通过以双下划线开头对类成员命名。但是可以通过对象._类__成员名进行访问。

4. 类的继承

Python的继承是多继承机制,父类是子类的进一步抽象。子类可以继承父类的方法。
重写父类的方法:在子类中重新定义了父类中已经定义的方法。
使用未绑定方法调用被重写后的方法:依据是可以通过类名访问类中的方法。

class Father:  
    def foo(self):  
        print("Father")  
  
class Son(Father):  
    def foo(self):  
        print("Son")  
    def bar(self):  
        print("Bar")  
        self.foo()  
        Father.foo(self)  
son = Son()  
son.bar()
Bar
Son
Father

使用super 函数调用父类的构造方法:

class Employee:  
    def __init__(self,salary):  
        self.salary = salary  
    def work(self):  
        print("Employee",self.salary)  
  
class Customer:  
    def __init__(self,favorite,address):  
        self.favorite = favorite  
        self.address = address  
    def info(self):  
        print("Customer",self.address,self.favorite)  
      
class Manager(Employee,Customer):  
    def __init__(self,salary,favorite,address):  
        print("Manager")  
        super().__init__(salary)  
        # super(Manager,self).__init__(salary)  
        Customer.__init__(self,favorite,address)  
m = Manager(2000,1,0)  
m.work()  
m.info()
Manager
Employee 2000
Customer 0 1

5. Python 的动态特性

6. 多态

7. 枚举类

posted @ 2023-10-28 16:26  何处惊雷  阅读(18)  评论(0)    收藏  举报