Python 之道

Python 3 学习笔记之——面向对象

2018-10-27  本文已影响0人  seniusen

1. 类的介绍

类(Class) 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例,类是对象的抽象。

2. 类的定义

语法格式如下:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
class person:
    
    instances = 0                # 类变量,所有类公用
    
    def __init__(self, name, age, weight):
        self.name = name         # 公有属性
        self.age = age
        self.__weight = weight   # 私有属性,在类外无法直接访问
        
        person.instances += 1;   # 通过类来访问类变量
    
    def tell_a_secret(self):     # 私有方法
        print("Tell you a secret, my weight is {} kg.".format(self.__weight))
    
    def speak(self):             # 公有方法
        print('My name is {}, I\'m {} years old.'.format(self.name, self.age))
        self.tell_a_secret()


people = person('seniusen', 21, 60)
people.speak()
print(people.instances)
print(people.instances) # 通过实例也可以访问类变量

# My name is seniusen, I'm 21 years old.
# Tell you a secret, my weight is 60 kg.
# 1
# 1

3. 类的单继承

语法格式如下:

class DerivedClassName(BaseClassName1):
    <statement-1>
    .
    .
    .
    <statement-N>
class student(person):
        
    def __init__(self, name, age, weight, major):
        
        person.__init__(self, name, age, weight) # 调用父类的构造函数,此时必须给定 self 参数
        # super(student, self).__init__(name, age, weight) 或者利用 super() 函数
        self.major = major

    # 重写父类的方法
    def speak(self): # 公有方法
        person.speak(self)
        print('My major in college is {}.'.format(self.major))

stu = student('seniusen', 21, 60, 'Automation')
stu.speak()
print(student.instances)
print(stu.instances) # 通过实例也可以访问类变量

# My name is seniusen, I'm 21 years old.
# Tell you a secret, my weight is 60 kg.
# My major in college is Automation.
# 2
# 2

3. 类的多继承

语法格式如下:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
class teacher:
      
    def __init__(self, title, topic):
        self.title = title 
        self.topic = topic
    
    def speak(self): # 公有方法
        print('I\'m a {} , my research topic is {}.'.format(self.title, self.topic))

# 继承自 teacher 和 student 的子类
class sample(teacher, student):
    
    def __init__(self, name, age, weight, major, title, topic):
        student.__init__(self, name, age, weight, major)
        teacher.__init__(self, title, topic)

test = sample('seniusen', 21, 60, 'Automation', 'prefessor', 'CV')
test.speak() # 没有指定方法,从左到右查找,这里调用了 teacher 类的 speak() 方法

# I'm a prefessor , my research topic is CV.

class Parent:           # 定义父类
    
    def myMethod(self):
        print ('Method form Parent class!')

        
class Child(Parent):    # 定义子类
    
    def myMethod(self):
        print ('Method form Child class!')

a = Child()                # 子类实例
a.myMethod()               # 子类调用重写方法
super(Child, a).myMethod() #用子类对象调用父类已被覆盖的方法

# Method form Child class!
# Method form Parent class!

参考资料 菜鸟教程

获取更多精彩,请关注「seniusen」!


上一篇 下一篇

猜你喜欢

热点阅读