class Student:#Student类名,有一个或多个单词组成,每个单词首字母大写,其余小写
def __init__(self,name,age):
self.name=name #self.name为实例属性,进行了一个赋值操作,将局部变量得到name的值赋给了实例属性
self.__age=age
#实例方法
def eat(self):
print(self.name+'吃饭了######')
stu1 = Student('张三',20)
print(dir(stu1))#在类的外部可以通过dir()查看访问方式,如_Student__age
print(stu1._Student__age)
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
class Teacher(Person):
def __init__(self,name,age,ttt):
super().__init__(name,age)
self.ttt = ttt
stu = Student('在上述',20,'111')
t = Teacher('离散',30,10)
stu.info()
t.info()
"""
多继承
"""
class A(object):
pass
class B(object):
pass
class C(A,B):
pass
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
def info(self):
super().info()#重写
print(self.stu_no)
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return '{0}今年{1}岁了'.format(self.name,self.age)
stu = Person('阿斯蒂芬',20)
print(stu)#默认调用__str__()方法,重写这个方法返回对象的描述
print(type(stu))
具有相同方法或属性!!!!
class Animal(object):
def eat(self):
print('动物会吃')
class Dog(Animal):
def eat(self):
print('狗吃肉')
class Cat(Animal):
def eat(self):
print('猫吃鱼')
class Person(object):
def eat(self):
print('人吃动物')
#定义一个函数
def fun(obj):
obj.eat()
#开始调用函数
fun(Cat())
fun(Dog())
fun(Animal())
print('-------------------------------------')
fun(Person())
__new__在前创建对象
__init__在后为对象实例属性赋值
class Person(object):
def __new__(cls, *args, **kwargs):
print('__new__被调用执行,cls的id值为{0}'.format(id(cls)))
obj = super().__new__(cls)
print('创建的对象的id为{0}'.format(id(obj)))
return obj
def __init__(self, name, age):
print('__init__被调用执行,self的id值为{0}'.format(id(self)))
self.name = name
self.age = age
print('object类对象的id值为{0}'.format(id(object)))
print('Person类对象的id值为{0}'.format(id(Person)))
p = Person('阿松大',20)
print('p的Person类的id值为{0}'.format(id(p)))