Python3 物件導向高階1

2022-08-18 10:57:14 字數 3128 閱讀 4504

目錄封裝

訪問限制

property

多型抽象類

鴨子型別

# 1

class other:

def func(self):

print('from other')

class foo:

def __init__(self):

self.other = other()

def func(self):

self.other.func()

foo = foo()

foo.func() # from other

# 2

class other:

def func(self):

print('from other')

class foo:

pass

foo = foo()

other_obj = other()

foo.func = other_obj.func

foo.func() # from other

class foo:

__name = 'bigb'

def __func(self):

print('secret')

foo = foo()

print(foo._foo__name) # bigb

foo._foo__func() # secret

# 1

class pyman:

language = 'python'

def __init__(self, name, age, gender):

self.__name = name

self.__age = age

self.__gender = gender

# 列印使用者資訊介面

def get_info(self):

username = input('請輸入使用者名稱: ')

password = input('請輸入密碼: ')

if username == 'bigb' and password == '123':

print(f'''

姓名:

年齡:

性別:

''')

# 修改使用者資訊介面

def set_info(self, name, age, gender):

if not isinstance(name, str):

raise typeerror

if not isinstance(age, int):

raise typeerror

if not isinstance(gender, str):

raise typeerror

self.__name = name

self.__age = age

self.__gender = gender

bigb = pyman('bigb', 18, 'male')

bigb.get_info()

bigb.set_info()

# 2

class atm:

def __insert_card(self):

print('插卡')

def __input_pwd(self):

print('輸入密碼')

def __input_money(self):

print('輸入金額')

def __get_monet(self):

print('執行吐錢')

def __print_bill(self):

print('列印賬單')

def withdraw(self):

self.__insert_card()

self.__input_pwd()

self.__input_money()

self.__get_monet()

self.__print_bill()

print('取款程式執行完畢!')

atm = atm()

atm.withdraw()

'''插卡

輸入密碼

輸入金額

執行吐錢

列印賬單

取款程式執行完畢!

'''

@property

class people:

def __init__(self, name, weight, height):

self.name = name

self.weight = weight

self.height = height

@property

def bmi(self):

return self.weight / (self.height * self.height)

bigb = people('bigb', 70, 1.8)

# 如果不用@property, 則print(bigb.bmi())

print(bigb.bmi)

import abc

import abc

class animal(metaclass=abc.abcmeta):

@abc.abstractmethod

def eat(self):

pass

@abc.abstractmethod

def drink(self):

pass

class pig(animal):

def eat(self):

print('pig is eating...')

peppa = pig()

typeerror: can't instantiate abstract class pig with abstract methods drink

父類方法被@abc.abstractmethod裝飾後, 子類必須也有相同的方法, 否則會報錯

Python3 基礎 物件導向高階程式設計(上)

在python中,我們可以動態的為類和物件繫結屬性和方法。給例項繫結屬性和方法 為例項繫結屬性 name class people pass p people p.name kd p.name kd print p.name kd 為例項繫結方法 def setage self,age self.a...

Python3學習筆記之物件導向高階程式設計

使用 property 在前面我們已經知道可以給類的例項繫結任何變數,而實際上作為動態語言的特點,不僅可以繫結變數,還可以給例項繫結方法,具體做法為 class student object pass.s student defset age self,age self.age age.from t...

物件導向 高階

json方式的物件導向 json 把方法包在json裡 json物件導向 有人管他叫 命名空間 在公司裡 把同一類 的方法包在一起 拖拽和繼承 物件導向的拖拽 改寫原有的拖拽 繼承 asdf 拖拽 instanceof 檢視物件是某個類的例項 使用繼承 限制範圍的拖拽類 建構函式的偽裝 屬性的繼承 ...