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()

3.@property方法 :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) #同上

4.@staticmethod静态函数

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)

猜你喜欢

转载自www.cnblogs.com/cjj-zyj/p/9946376.html