1. 程式人生 > >python3面向物件常用特性知識點

python3面向物件常用特性知識點

1.常用跨類方法

class test:

    def run(self):
        print(1)
class test1(test):
    def run1(self):
        test().run()

if __name__ == '__main__':
    test1().run1()  #非繼承也可用

注意__init__方法其實是建立一個空物件然後再進行賦值

 

2.抽象類 :必須要繼承abc的抽象方法,以abc裝飾器來判斷是否是抽象類,子類重寫父類的介面方法

import abc  #匯入abc模組
class
InMa(metaclass=abc.ABCMeta): #定義抽象方法 @abc.abstractmethod #定義抽象方法 def login(self): pass @abc.abstractmethod def zhuce(self): pass class Login(InMa): #繼承抽象類 def __inti__(self,name,pwd): self.name = name self.password = pwd def login(self): #實現抽象方法功能
if self.name == "qq" and self.password == "111": print("恭喜登入成功") else: print("登入失敗") class Zc(Login): def __init__(self,name,pwd): self.name = name self.password = pwd def zhuce(self): print("恭喜註冊成功") print("username:",self.name) print
("password:",self.password) #例項物件 ren = Zc("Jaue","qqq") ren.zhuce()

[email protected]方法 :property是一種特殊的屬性,訪問它時會執行一段功能(函式)然後返回值 # obj.介面 直接呼叫

import math
class Circle:
    def __init__(self,radius): #圓的半徑radius
        self.radius=radius

    @property
    def area(self):
        return math.pi * self.radius**2 #計算面積

    @property
    def perimeter(self):
        return 2*math.pi*self.radius #計算周長

c=Circle(10)
print(c.radius)
print(c.area) #可以向訪問資料屬性一樣去訪問area,會觸發一個函式的執行,動態計算出一個值
print(c.perimeter) #同上

[email protected]靜態函式

import time
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now(): #用Date.now()的形式去產生例項,該例項用的是當前時間
        t=time.localtime() #獲取結構化的時間格式
        return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建例項並且返回
    @staticmethod
    def tomorrow():#用Date.tomorrow()的形式去產生例項,該例項用的是明天的時間
        t=time.localtime(time.time()+86400)
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

a=Date('1987',11,27) #自己定義時間
b=Date.now() #採用當前時間
c=Date.tomorrow() #採用明天的時間
#重點: a是例項,b,c都是類也直接呼叫

print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)

@classmethod與@staticmethod

• 使用場景:classmethod在一些工廠類的情況下使用較多,也就是說OOP裡繼承的時候使用,
staticmethod一般情況下可以替換為外部的函式,後者繼承的時候不可更改,和C++/JAVA中的靜態方法很相似

• 有利於組織程式碼,同時有利於名稱空間的整潔

以上這篇基於python中staticmethod和classmethod的區別(詳解)就是小編分享給大家的全部內容了,
希望能給大家一個參考,也希望大家多多支援指令碼之家。
class A(object):
    def foo(self, x):
        print("executing foo(%s,%s)" % (self, x))

    @classmethod
    def class_foo(cls, x):
        print("executing class_foo(%s,%s)" % (cls, x))

    @staticmethod
    def static_foo(x):
        print("executing static_foo(%s)" % x)


a = A()
print(a.foo)
# <bound method A.foo of <__main__.A object at 0x0375B450>>

print(a.class_foo)
# <bound method A.class_foo of <class '__main__.A'>>

print(A.class_foo)
# <bound method A.class_foo of <class '__main__.A'>>

print(a.static_foo)
# <function A.static_foo at 0x07CAE6F0>
print(A.static_foo)
# <function A.static_foo at 0x07CAE6F0>

 5.私有變數,方法

class pub():
    _name = 'protected型別的變數'
    __info = '私有型別的變數'
    def _func(self):
        self.__func2()
        print("這是一個protected型別的方法")
    def __func2(self):
        print('這是一個私有型別的方法')
    def get(self):
        return(self.__info)

a = pub()
print(a._name)
a._func()
# a.__func2() 報錯

6.setter getter 用於判斷變數,重寫私有變數

判斷變數格式

class Person(object):

    __privateVal=100

    def __init__(self, name):
        self.name = name

    @property
    def name(self):
        print("getter 被呼叫")
        return self._name

    @name.setter
    def name(self, name):
        print("setter 被呼叫")
        if not isinstance(name, str):
            raise TypeError("型別不匹配,應該為字串型")
        self._name = name

person = Person("Tom")
print(person.name)

重寫私有變數

class Person:
    # 只允許擁有私有的name和age屬性
    __slots__ = ('__name', '__age')
    def __init__(self,name,age):
        self.__name=name
        self.__age=age

    @property
    def name(self):
        return self.__name
    @name.setter
    def name(self,name):
        print("setter開始")
        self.__name=name

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        print("getter開始")
        # self.__age = age
    def __str__(self):
        return '姓名 '+self.__name+' \n年齡'+str(self.__age)
if __name__=='__main__':
    zhangsan=Person('張三',20)
    print(zhangsan)
    print(zhangsan.name)
    print(zhangsan.age)
    zhangsan.age=30
    zhangsan.name='張三三'
    print(zhangsan)