python 面向对象_2

时间:2019-11-14
本文章向大家介绍python 面向对象_2,主要包括python 面向对象_2使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

self的理解

通俗理解self就是实例对象,实例化的是什么,self就是什么

实例变量: 经过实例化才能使用的变量

class Person():
    def __init__(self,id,name):#构造函数
        self.id = id#实例变量
        self.name = name#实例变量

    def cook(self):
        print('%s在做饭'%self.name)

    def housework(self):
        print('%s在做家务'%self.name)

xh = Person(1,'小黑')#等同于__init(self,id,name) self其实就是xh
xh.cook()
xh.housework()
xb = Person(2,'小白')
xb.cook()

类变量: 定义在类里面的变量,类的对象优先获取实例变量,也就是构造函数中变量的,如果获取不到就会获取类变量

class Test:
    name = 'haha'
    def __init__(self,name):
        # self.name = name
        pass
    def test(self):
        print('姓名是%s'%self.name)

t=Test('ahah')
print(t.name)

类方法:不用实例化即可调用的方法,类名可直接调用,实例也可以调用,类方法可以调用类变量

class Test:

    name = 'haha'

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

    def test(self):
        print('姓名是%s'%self.name)

    @classmethod #加上这个装饰器就是定义一个类方法
    def sayCountry(cls):    #cls代表本身的这个类'Test'
        print(cls.name)

t=Test('ahah')
print(t.name)
Test.sayCountry()#类方法,不需要实例化,通过类名直接调用;用实例也能调用

静态方法:无法调用类变量,无法调用类方法;    类名可以直接调用它,实例也可直接调用它

class Test:

    name = 'haha'

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


    def test(self):
        print('姓名是%s'%self.name)

    @classmethod #加上这个装饰器就是定义一个类方法
    def sayCountry(cls):    #cls代表本身的这个类'Test'
        print(cls.name)

    @classmethod
    def getCountry(cls):
        cls.sayCountry()#类方法可互相调用

    @staticmethod #加上这个装饰器就是定义一个静态方法,无法调用类变量和类方法
    def help():
        print('说明书')

t=Test('ahah')
print(t.name)
Test.sayCountry()#类方法,不需要实例化,通过类名直接调用;用实例也能调用
Test.help()
Test.getCountry()

属性方法:看起来像变量的一个方法,不能用参数

class Test:

    name = 'haha'

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

    def test(self):
        print('姓名是%s'%self.name)

    @classmethod #加上这个装饰器就是定义一个类方法
    def sayCountry(cls):    #cls代表本身的这个类'Test'
        print(cls.name)

    @classmethod
    def getCountry(cls):
        cls.sayCountry()#类方法可互相调用

    @staticmethod #加上这个装饰器就是定义一个静态方法,无法调用类变量和类方法
    def help():
        print('说明书')

    @property
    def price(self):#属性方法,不能用参数
        print(self.age)

t=Test('ahah',10)
print(t.name)
Test.sayCountry()#类方法,不需要实例化,通过类名直接调用;用实例也能调用
Test.help()
Test.getCountry()
t.price   #不用加括号,引用方式和引用属性(变量)一致

原文地址:https://www.cnblogs.com/mhmh007/p/11857312.html