python基础(class)

python基础(class)

1.类方法与静态方法

代码:
类方法

class Student():
   number = "90"
   
   def __init__(self,name,age):
      self.name = name
      self.age = age
   
   @classmethod
   def printNum(cls):
      print(cls.number)
      # print(self.name) (error,类方法和静态方法不能调用实例属性和方法)
Student.printNum()
90

  1. @classmethod 必须位于方法上面一行 第一个 cls 必须有;
  2. cls 指的就是“类对象”本身;
  3. 调用类方法格式:“类名.类方法名(参数列表)”。
  4. 参数列表中,不需要也不能给 cls 传 值。
  5. 类方法中访问实例属性和实例方法会导致错误
  6. 子类继承父类方法时,传入 cls 是子类对象,而非父类对象

静态方法
“静态方法”和在模块中定义普通函数没有区别,只不过“静态方法”放到了“类的名字空 间里面”,需要通过“类调用”。

class Student():
   number = "90"
   
   @staticmethod
   def add(a,b):
      print("{0}+{1}={2}".format(a,b,a+b))
Student.add(11,22)
11+22=33

2.析构函数

代码如下(示例):

class Test():
    
    def __del__(self):
        print("销毁:{0}".format(self))
        
p1 = Test()
p2 = Test()
del p2
print("Over")
销毁:<__main__.Test object at 0x7fe4d6832f90>
销毁:<__main__.Test object at 0x7fe4d682cf90>
Over

3.调用__call__

class SalaryCount():
    
    def __call__(self,salary):
        yearSalary = salary*12
        daySalary = salary//22.5
        
        return dict(yearSalary = yearSalary, monthSalary = salary, daySalary = daySalary)
    
s = SalaryCount()
print(s(20000))
 {'yearSalary': 240000, 'monthSalary': 20000, 'daySalary': 888.0}

4.python没有重载

Python 中,方法的的参数没有声明类型(调用时确定参数的类型),参数的数量也可以由可变参数控制。因此,Python中是没有方法的重载的。定义一个方法即可有多种调用方式, 相当于实现了其他语言中的方法的重载。
 如果我们在类体中定义了多个重名的方法,只有最后一个方法有效。
 建议:不要使用重名的方法!Python 中方法没有重载。

5.私有方法

class Master_degree():
    
    __school = "USYD" ##私有化
    
    def __init__(self,name,age):
        self.name = name
        self.__age = age  ##私有化
        
    def Cv(self):
        print("My school is:", self.__school)
        print("My name is:", self.name, "age:", self.__age)
        self.__course
        
        
    def __course(self):
        print("Course:5046-nlp")

m1 = Master_degree("James",22)
print(m1.name)
print(m1._Master_degree__school)
print(dir(m1))
m1._Master_degree__course()
#m1.__course() 直接访问私有属性会报错
m1.Cv()
James
USYD
['Cv', '_Master_degree__age', '_Master_degree__course', '_Master_degree__school', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
Course:5046-nlp
My school is: USYD
My name is: James age: 22

6.property 装饰器

进行读取修改

class Employee():
    
    def __init__(self,name,salary):
        self.__name = name
        self.__salary = salary
        
    @property
    def salary(self):
        return self.__salary
        
    @salary.setter
    def salary(self,salary):
        if 1000<salary<10000:
            self.__salary = salary
        else:
            print("salary number error!")

emp1 = Employee("James",30000)
print(emp1.salary)
emp1.salary = 5000
print(emp1.salary)
emp1.salary = 500
print(emp1.salary)
30000
5000
salary number error!
5000

7.继承

class Person():
    
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    
class Student(Person):
    
    def __init__(self,name,age,school):
        Person.__init__(self,name,age)
        self.school = school
        
jame = Student("Jame",19,"USYD")
print(jame.name)
print(jame._Person__age) ##子类继承父类除构造方法外所有成员但不能直接调用私有属性
Jame
19

8.重写

class Person():
    
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    
    def intro(self):
        print("My name is:",self.name)
        
class Student(Person):
    
    def __init__(self,name,age,school):
        Person.__init__(self,name,age)
        self.school = school
     
    def intro(self):
        print("My English name is:",self.name)
        
jame = Student("Jame",19,"USYD")
jame.intro()
My English name is: Jame

9.object根类_dir()

 dir():查看类所有属性
 mro()或者类的属性__mro__可以输出这个类的继承层次结构

10.重写__str__()方法

class Person:
    def __init__(self,name,age): 
        self.name = name 
        self.__age = age

p = Person("Jame",18)
print(p)
<__main__.Person object at 0x7fe4d68afed0>

重写:

class Person:
    def __init__(self,name,age): 
        self.name = name 
        self.__age = age

    def __str__(self):
        return "name is:{0},age is {1}".format(self.name,self.__age)

p = Person("Jame",18)
print(p)
name is:Jame,age is 18

11.python可以实现多重继承

MRO(Method Resolution Order):方法解析顺序。 我们可以通过 mro()方法获得 “类的层次结构”

12.super()

在子类中,如果想要获得父类的方法时,可以通过 super()

class A:
    def say(self):
        print("A: ",self) 
        print("say AAA")

class B(A):
    def say(self):
        #A.say(self) 调用父类的 say 方法 
        super().say() #通过 super()调用父类的方法 
        print("say BBB")

b = B()
b.say()
A:  <__main__.B object at 0x7fe4d6a169d0>
say AAA
say BBB

13.多态

class Animal:
    def shout(self):
        print("动物叫了一声")

class Dog(Animal):
    def shout(self):
        print("小狗,汪汪汪")

class Cat(Animal):
    def shout(self):
        print("小猫,喵喵喵")

def animalShout(a):
    if isinstance(a,Animal):
        a.shout() #传入的对象不同,shout 方法对应的实际行为也不同。

animalShout(Dog()) 
animalShout(Cat())
小狗,汪汪汪
小猫,喵喵喵

14. 运算符重载与特殊属性

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
重写运算符:

class Person:
    def __init__(self,name): 
        self.name = name
    
    def __add__(self, other):
        
        if isinstance(other,Person):
            return "{0}-{1}".format(self.name,other.name) 
        else:
            return "not the same calss,can not adding"
    
    def __mul__(self, other):
        
        if isinstance(other,int):
            return self.name*other 
        else:
            return "not the same calss,can not multiply"

p1 = Person("James")

p2 = Person("Harry")

x = p1 + p2

print(x)

print(p1*5)
 James-Harry
 JamesJamesJamesJamesJames

特殊属性:

class A:
    pass

class B:
    pass

class C(B,A):
    
    def __init__(self,nn):
        self.nn = nn
    
    def cc(self):
        
        print("cc")

c = C(3)

print(dir(c)) 
print(c.__dict__) 
print(c.__class__) 
print(C.__bases__) 
print(C.mro()) 
print(A.__subclasses__())
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cc', 'nn']
{'nn': 3}
<class '__main__.C'>
(<class '__main__.B'>, <class '__main__.A'>)
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
[<class '__main__.C'>]

·浅拷贝

Python 拷贝一般都是浅拷贝。拷贝时,对象包含的子对象内容不拷贝。因此,源对象 和拷贝对象会引用同一个子对象。

·深拷贝

使用 copy 模块的 deepcopy 函数,递归拷贝对象中包含的子对象。源对象和拷贝对象 所有的子对象也不同。

15.组合

class MobilePhone:
    
    def __init__(self,cpu,screen):
        self.cpu = cpu 
        self.screen = screen

class CPU:
    
    def calculate(self):
        print("Calculating something ....")

class Screen:
    
    def show(self):
        print("What a wonderful screen!")
        
c = CPU() 
s = Screen() 
m = MobilePhone(c,s) 
m.cpu.calculate() #通过组合,我们也能调用 cpu 对象的方法。相 当于手机对象间接拥有了“cpu 的方法” 
m.screen.show()
Calculating something ....
What a wonderful screen!

16.工厂模式,单例模式

class Model:
    
    __obj = None #类属性 
    __init_flag = True
    
    def bulid_model(self,name):
        
        if name =="RNN":
            return RNN() 
        elif name =="CNN":
            return CNN() 
        elif name == "MLP":
            return MLP()
        else:
            return "nuknow model"
        
    def __new__(cls, *args, **kwargs):
        
        if cls.__obj == None:
            cls.__obj = object.__new__(cls)
            
        return cls.__obj
        
    def __init__(self):
        
        if Model.__init_flag:
            print("init Model....") 
            Model.__init_flag = False
            
class CNN:
    
    pass

class MLP:

    pass

class RNN:

    pass

model = Model() 
m1 = model.bulid_model("CNN") 
m2 = model.bulid_model("RNN") 
print(m1) 
print(m2)
model2 = Model() 
print(model) 
print(model2)
init Model....
<__main__.CNN object at 0x7fe4d68ac310>
<__main__.RNN object at 0x7fe4d68acbd0>
<__main__.Model object at 0x7fe4d68ac350>
<__main__.Model object at 0x7fe4d68ac350>

猜你喜欢

转载自blog.csdn.net/weixin_47018261/article/details/112728880
今日推荐