Python学习 —— 面向对象(Class)

版权声明:转载注明出处 https://blog.csdn.net/qq_19428987/article/details/85838270

和C++/C#类似,Python也是一种面向对象的设计语言。用Class来进行定义。

class Person:
	#全局属性(public)
	name=None
	age=18
	def __init__(self,a,b):#默认构造函数,系统自动调用
		self.name=a
		self.age=b
   def  ShowMessage():
   		print("{0} is {1} years old".format(self.name,self.age))
  • 在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例;
  • 同样Python中的类也支持继承:
class Student(Person):
	#私有属性(private)
	__source=0
	del __init__(self,a,b,c):
		self.name=a
		self.age=b
		self.__source=c
	del ShowMessage():
		print("{0} get {1}".format(self.name,self.__source))
		

上列中举了一个单继承的例子,同样Python中也可以支持多继承

class Teache(Person,Student):
	pass

需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。

  • 两个下划线开头,声明该属性为私有(private),不能在类的外部被使用或直接访问;一个下划线开头,声明该属性为保护类型(protect)只能在该类和改类的派生类中访问;没有下划线开头的就是共有属性(public)可以在类的内外部访问。
  • super() 函数是用于调用父类(超类)的一个方法,多继承时从左往右一次匹配:
c=Student(self,"Yhz",18,200)
c.ShowMessage()
super(Student,c).ShowMessage() #用子类对象调用父类已被覆盖的方法

上列中输出为:
Yhz get 200
Yhz is 18 years old

类中专用的方法

 __init__:构造函数,在生成对象时调用;
 __del__ : 析构函数,释放对象时使用

附加学习代码:

class person:
    name="XXX"
    age=0
    def __init__(self,m_name,m_age):
        self.name=m_name
        self.age=m_age

    def GetName(self):
        return self.name
    def GetAge(self):
        return  self.age
    def ShowMessage(self):
        print("{0} is {1} years old!".format(self.name,self.age))
class student(person):
    __source=0
    def __init__(self,m_name,m_age,m_sourece):
        self.__source=m_sourece
        super().__init__(m_name,m_age)
    def ShowMessage(self):
        print("{0}'s source is {1}".format(self.name,self.__source))
class teacher(student,person):
    def __init__(self,m_name,m_age,m_sourece):
        super().__init__(m_name,m_age,m_sourece)
a=person("Angle",18)
a.ShowMessage()
print(person.name)
b=student("Bable",12,85)
b.ShowMessage()
super(student,b).ShowMessage()#超类访问
print(student.name)
print("-----------------------")
t=teacher("Bable",12,85)
t.ShowMessage()
super(student,t).ShowMessage()

输出结果:

Angle is 18 years old!
XXX
Bable's source is 85
Bable is 12 years old!
XXX
-----------------------
Bable's source is 85
Bable is 12 years old!

猜你喜欢

转载自blog.csdn.net/qq_19428987/article/details/85838270
今日推荐