python面向对象编程
Posted zhujunjie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python面向对象编程相关的知识,希望对你有一定的参考价值。
继承介绍:
class Parent1(object):
pass
class Parent2:
pass
class Sub1(Parent1):
pass
class Sub2(Parent1,Parent2):
pass
print(Sub1.__bases__)
print(Sub2.__bases__)
print(Parent1.__bases__)
print(Parent2.__bases__)
class Foo:
x=1
pass
obj=Foo()
obj.x=3
print(obj.x)
继承解决类与类代码冗余的问题:
class OldboyPeople:
school = ‘Oldboy‘
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
print(OldboyPeople.__init__)
class OldboyStudent(OldboyPeople):
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def choose_course(self):
print(‘%s is choosing course‘ %self.name)
class OldboyTeacher(OldboyPeople):
def __init__(self,name,age,gender,level,salary):
self.name = name
self.age = age
self.gender = gender
OldboyPeople.__init__(self,name,age,gender)
self.level=level
self.salary=salary
def score(self,stu,num):
stu.num=num
print(‘老师%s给学生%s打分%s‘ %(self.name,stu.name,num))
stu=OldboyStudent(‘kevin‘,38,‘male‘) #__init___(stu1,‘kevin‘,38,‘male‘)
print(stu.__dict__)
tea=OldboyTeacher(‘egon‘,18,‘male‘,10,3000) #__init___(tea,‘egon‘,18,‘male‘,10,3000)
print(tea.__dict__)
print(stu.school)
print(tea.school)
单继承背景下属性的查找顺序:
class Foo:
def f1(self):
print(‘Foo.f1‘)
def f2(self):
print(‘Foo.f2‘)
self.f1() #obj.f1()
class Bar(Foo):
def f1(self):
print(‘Bar.f1‘)
obj=Bar()
obj.f2()
class E:
xxx=‘E‘
pass
class F:
xxx=‘F‘
pass
class B(E):
xxx=‘B‘
pass
class C(F):
xxx=‘C‘
pass
class D:
xxx=‘D‘
pass
class A(B,C,D):
xxx=‘A‘
pass
# obj=A()
# obj.xxx=111
# print(obj.xxx)
print(A.mro())
class G:
xxx=‘G‘
class E(G):
xxx=‘E‘
pass
class F(G):
xxx=‘F‘
pass
class B(E):
xxx=‘B‘
pass
class C(F):
xxx=‘C‘
pass
class D(G):
xxx=‘D‘
pass
class A(B,C,D):
xxx=‘A‘
pass
print(A.mro())
以上是关于python面向对象编程的主要内容,如果未能解决你的问题,请参考以下文章