10_Object-oriented_Programming

类名称的首字母要大写

类中__init__()方法在创建实例时自动运行。

self对应实例的名称,不同的实例有不同的属性和方法。

class Dog():
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def sit(self):
        print(self.name.title() + " is now sitting.")
 
    def roll_over(self):
        print(self.name.title() + " rolled over!")

类的继承

通过super()函数继承。

class Car():
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name="{} {} {}".format(self.year,\
        self.make,self.model)
        return long_name.title()

class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)

open/closed_principle:Software entities should be open for extension, but closed for modification.

另外两种继承方式:

pass原样照搬

class Person:
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex
        
    def print_title(self):
        if self.sex == "male":
            print("man")
        elif self.sex == "female":
            print("woman")
 
class Child(Person):                            
    pass

用父类名字继承

class Person:
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex
        
    def print_title(self):
        if self.sex == "male":
            print("man")
        elif self.sex == "female":
            print("woman")
 
class Child(Person):                            
    def __init__(self,name,sex):
        Person.__init__(self,name,sex)

三种继承方式在单个的继承中没有区别,在多重继承中有区别

多重继承:一个子类有多个父类,较为复杂,使用super()可以确定关系。

判断实例、判断类的父子关系的函数:

class Person:
    pass
class Child(Person):                 
    pass
May = Child()
Peter = Person()

print(isinstance(May,Child))         # True
print(isinstance(May,Person))        # True
print(isinstance(Peter,Child))       # False
print(isinstance(Peter,Person))      # True
print(issubclass(Child,Person))      # True

__xxx__

所有类,包括列表,字典,字符串以及自定义的类等,都继承于object类,它是一个最基础的类。

class A:classA(object):是等价的。

__xxx__型的函数规定一些底层的运算规则,在创建类时也可以修改。

class Dog():
    "This is about dog class."
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
print(Dog.__doc__)
print(Dog.__name__)
print(Dog.__module__)
print(Dog.__bases__)

"""
This is about dog class.
Dog
__main__
(<class 'object'>,)
"""

import class

"""
from file_name import class_name_1,class_name_2,...,class_name_n
"""
from car import Car, ElectricCar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值