12面向对象三

一.类属性和实例属性

class Person(object):

country ='china'#类属性

    def __init__(self,name,country):

self.name = name

self.country = country#实例属性

    #如果对象上没有country属性,那么通过self.country和Person.country

    #效果是一样的,都是访问Person的类属性

    #如果对象绑定了country属性,那么通过self.country访问到的就是这个对象上的属性

    #通过Person.country访问到的就是类属性。

    def greet(self):

print('my name is %s,my age is %d'%(self.name,Person.country))#self.country

#实例属性

#绑定到对象上的属性就是实例属性

#实例属性只在当前对象上有用

# p1 = Person('zhiliao')

# p1.age = 18

# print(p1.age)

# print(p1.name)

#

# p2 = Person('xuxu')

# print(p2.name)

# print(p2.age)#报错

#类属性

#如何在类中定义类属性

#类属性可以通过对象进行访问

#如果通过对象修改类属性,那么其实不是修改类属性,而是在这个对象上面重新定义了

#一个名字相同的实例属性

p1 = Person('zhiliao')

p1.country ='usa'

print(p1.country)

p2 = Person('xuxu')

p2.country ='canada'

print(p2.country)

print(Person.country)

#要正确的修改类属性,只能通过类名的方式修改

Person.country ='abc'

print(Person.country)

二.类方法和实例方法

class Person(object):

def eat(self):

print('hewllo,word')

@classmethod#加装饰器,就变成了类的方法

    #类方法:第一个参数必须是cls,这个cls代表的是当前这个类

    def greet(cls):

print('zhiliaoketang1')

@staticmethod#静态方法,不需要传递参数(self或cls)

    #静态方法使用场景:不需要修改类或者对象属性的时候,并且这个方法放在这个类中

    #可以让代码更加有管理性

    def start_method():

print('hello')

#实例方法2

# p1 = Person()

# p1.eat()

# Person.eat()#报错

#类方法

#调用方式

#1。使用类名

# Person.greet()

#2.使用对象

# p1 = Person()

# p1.greet()

#静态方法

# Person.start_method()

# p1 = Person()

# p1.start_method()

三.__new__()方法

#__new__方法

#创建对象(__new__),初始化对象(__init__)

class Car(object):

def __new__(cls, *args, **kwargs):

print('hello')

#return none

        #一定要切记,必须要在new方法后面返回这个类的对象

        return super(Car,cls).__new__(cls,*args, **kwargs)

def __init__(self):

print('car init method')

car = Car

print(car)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 5,866评论 2 16
  • 初识面向对象 楔子 你现在是一家游戏公司的开发人员,现在需要你开发一款叫做<人狗大战>的游戏,你就思考呀,人狗作战...
    go以恒阅读 947评论 0 6
  • 1.1面向对象 面向对象(object-oriented ;简称: OO)至今还没有统一的概念 我这里把它定义为:...
    TENG书阅读 584评论 0 0
  • * 时异境迁,佛教在本土的发展弘传中,由于种种的历史原因,人们在阐述佛教的信仰时,对佛陀所觉证的根本佛法产生了五戒...
    知梦阅读 285评论 0 0
  • #心灵自由写作群# 2018.6.2,6 第20篇 正如每个人的出生星图不同,每个人今世的灵魂使命也不同。出生星图...
    菲梵飞阅读 1,194评论 0 0