创建类:

class 类名(父类):
属性
方法 (如果在方法里直接定义属性,那么只有在改方法执行后,该属性才能被访问)

创建对象:

  • 对象名=类名(参数)
  • 对象.属性
  • 对象.方法

    对象的内置方法:

    new:真正的类构造方法,用于产生实例化对象。 ```python

    单例模式

    class Student: instance = None def new__(cls, args, *kwargs):
    1. if not cls.__instance:
    2. cls.__instance = object.__new__(cls)
    3. return cls.__instance

stu1 = Student() stu2 = Student() print(id(stu1), id(stu2)) # 两者输出相同 print(stu1 is stu2) # True

  1. __init__:方法是初始化方法,负责对实例化对象进行属性值初始化<br />__str__:在使用时调用,与__repr__功能相似,只不过不是在控制台输出时调用<br />__repr__:被控制台输出时默认调用,方便查看和调试
  2. ```python
  3. def __str__(self):
  4. return .....
  5. __repr__=__str__

del:一般用于需要声明在对象被删除前需要处理的资源回收操作
call:将一个类实例变成一个可调用对象

  1. class Person(object):
  2. def __init__(self, name, gender):
  3. self.name = name
  4. self.gender = gender
  5. def __call__(self, friend):
  6. print('My name is %s...' % self.name)
  7. print('My friend is %s...' % friend)
  8. p = Person('Bob', 'male')
  9. p('Tim')
  10. '''
  11. My name is Bob...
  12. My friend is Tim...
  13. '''

私有属性与方法

私有属性与方法
_xxx “单下划线 “ 开始的成员变量叫做保护变量,意思是只有类对象(即类实例)和子类对象自己能访问到这些变量
__xxx 类中的私有变量/方法名 ,” 双下划线 “ 开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。

  • 私有的属性,不能通过对象直接访问,但是可以通过方法访问
  • 私有的方法,不能通过对象直接访问
  • 私有的属性、方法,不会被子类继承,也不能被访问
  • 一般情况下,私有的属性、方法都是不对外公布的,往往用来做内部的事情,起到安全的作用

    继承:

    ```python class Animal: def init(self,color):
    1. self.color=color
    def eat(self):
    1. print("吃东西")
    def show(self):
    1. print(self.color)

class Cat(Animal): def init(self,color):

  1. # 父子类是由__init__实现的,如果父类__init__()无参数,这句话可以不写,默认就有
  2. Animal.__init__(self,color)
  3. pass

dog=Animal(“黑色”) dog.show() c=Cat(“白色”) c.show()

  1. <a name="sCsQs"></a>
  2. ### 多继承:
  3. ```python
  4. class Father:
  5. money=100
  6. def __init__(self,x):
  7. self.x=x
  8. class Money:
  9. money=10
  10. face="好看"
  11. def __init__(self,y):
  12. self.y=y
  13. class Son(Money,Father): #这里的Money,Father要有顺序,这里去找一个变量,先会从Money类找,
  14. def __init__(self,x,y): #当Money类没有时,才会去Father找
  15. Money.__init__(self,y)
  16. Father.__init__(self,x)
  17. s=Son(3,4)
  18. print(s.money)
  19. print(s.x) #3
  20. print(s.y) #4

多态:

  1. class Aniaml:
  2. def eat(self):
  3. print("啥都吃")
  4. class Dog(Aniaml):
  5. def eat(self):
  6. print("吃骨头")
  7. class Cat(Aniaml):
  8. def eat(self):
  9. print("吃鱼")
  10. class Persion:
  11. def feed(self,Animal):#Animal表示我要喂哪个动物,这个例子是传入Animal的子类对象
  12. Animal.eat()
  13. c = Cat()
  14. d = Dog()
  15. p = Persion()
  16. p.feed(c)
  17. p.feed(d)

重写:

  1. '''
  2. 重写:当父类的属性与方法不满足子类的需求时,可以重写
  3. 要求:子类与父类方法名一样即可,一旦重写,子类对象看不到父类的方法
  4. '''
  5. class Animal :
  6. color="黑色"
  7. def eat(self):
  8. print("啥都吃")
  9. def play(self):
  10. print("乱蹦乱跳")
  11. class Cat(Animal):
  12. color="白色"
  13. def eat(self,name):
  14. print(name+"猫吃鱼")
  15. c=Cat()
  16. c.eat("Tom")
  17. c.play()
  18. print(c.color)

动态添加属性与方法:

  1. import types
  2. class Person:
  3. def __init__(self,name,age):
  4. self.name=name
  5. self.age=age
  6. p1=Person("张三",20)
  7. p1.sex="男" #对象给类添加属性,只对当前对象有效
  8. Person.sex="女" #类本身添加属性,对类的对象都起作用
  9. #添加方法
  10. def run(self):
  11. print("蹦蹦跳跳")
  12. p1.personrun=types.MethodType(run,p1) #对象给类添加方法,只对当前对象有效
  13. Person.personsay=say #类本身添加方法,对类的对象都起作用

super函数:

  1. #super用于字节调用父类的函数
  2. class A:
  3. def add(self, x):
  4. y = x+1
  5. return y
  6. class B(A):
  7. def add(self, x):
  8. result=super().add(x)
  9. return result*2
  10. b = B()
  11. b.add(2) # 6

类的方法:

  1. class Root:
  2. def __init__(self): #构造方法,只在创建对象时自动调用
  3. pass
  4. def show(self): #普通方法,只有对象能够调用
  5. pass
  6. @classmethod
  7. def show(cls): #声明类方法,cls可以传实参可以不传实参,但是要写上
  8. pass #可以用对象和类名调用
  9. @staticmethod #静态方法,不用传参,可以用对象和类名调用
  10. def show():
  11. pass

@property

在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数
为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数:

  1. class Student(object):
  2. def get_score(self):
  3. return self._score
  4. def set_score(self, value):
  5. if not isinstance(value, int):
  6. raise ValueError('score must be an integer!')
  7. if value < 0 or value > 100:
  8. raise ValueError('score must between 0 ~ 100!')
  9. self._score = value
  10. s = Student()
  11. s.set_score(60) # ok!
  12. s.get_score()
  13. 60

这样明显太麻烦,因此@property就出来了

  1. class Student(object):
  2. @property
  3. def score(self):
  4. return self._score
  5. @score.setter
  6. def score(self, value):
  7. if not isinstance(value, int):
  8. raise ValueError('score must be an integer!')
  9. if value < 0 or value > 100:
  10. raise ValueError('score must between 0 ~ 100!')
  11. self._score = value
  12. s=Student
  13. s.score=50 #实际转化为s.set_score(50)
  14. s.score>>>50 #实际转化为s.get_score(50)

@abstractmethod

抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化。
Python的abc提供了@abstractmethod装饰器实现抽象方法

见下图的代码,基类Foo的fun方法被@abstractmethod装饰了,所以Foo不能被实例化;子类SubFoo没有实现基类的fun方法也不能被实例化;子类SubB实现了基类的抽象方法fun所以能实例化。

  1. from abc import ABC, abstractmethod
  2. class Foo(ABC):
  3. @abstractmethod
  4. def fun(self):
  5. '''please Implemente in subclass'''
  6. class FooA(Foo):
  7. def run(self):
  8. print('run in FooA')
  9. class FooB(Foo):
  10. def fun(self):
  11. print('fun in FooB')
  12. a = FooA()#TypeError: Can't instantiate abstract class FooA with abstract methods fun
  13. b = FooB()
  14. b.fun()