写在最前:本文为个人学习成果展示,不是教程,别来参考,进来后退出就好,文章可能有误,总之,别参考这篇文章
类
初始化
字段
继承
多态
对象的创建
不限位数的形参
类的其他属性
dict
class
base
mro
subclasses
复制
浅拷贝
深拷贝
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return '我叫' + self.name
def eat(self):
print('我能吃')
def drink(self):
print('我能喝')
class Student(Person): # 可以多个父类
kind = 'Person'
def __init__(self, name, age, gender):
super().__init__(self, name)
self.age = age
self.__gender = gender # 加__为不希望在外部使用的属性
def __init__(self, name):
self.name = name
@staticmethod
def eat():
print('我爱吃饭')
def say_name(self):
print('我的名字叫{0}'.format(self.name))
@classmethod
def cm(cls):
print('学生类')
stu1 = Student('张三')
stu1.say_name()
Student.cm()
stu1.eat()
print(dir(Person))
print(stu1) # 见__str__()
class Animal:
def __init__(self, age, size):
self.age = age
self.size = size
class Cat(Animal):
def __init__(self, age, size):
super().__init__(age, size)
def __init__(self, name):
self.name = name
def __add__(self, other): # 加法
return '两只小猫'
def __len__(self): # 长度
return len(self.name)
def __new__(cls, *args, **kwargs):
print('new被执行了')
obj = super().__new__(cls)
return obj
print('*********************************************************************')
an1 = Animal(2, 1)
cat1 = Cat('小花')
print(an1.__dict__)
print(Animal.__dict__)
print(an1.__class__)
print(Animal.__bases__) # _base_输出写在最前的继承
print(Cat.__mro__) # 类的层次结构
print(Animal.__subclasses__()) # 子类列表
'''复制
1.直接用=会成为引用传递
2.浅拷贝,只拷贝源对象,不拷贝子类对象
利用copy
import copy
b = copy.copy(a)
本身不一样,子类一样
3.深拷贝,源对象和被拷贝对象的子对象都不一样
import copy
d = copy.deepcopy(c)
'''