Python进阶8---面向对象基础1
面向对象
语言的分类
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
Python的类
定义
class ClassName: pass
class MyCalss: """A example class"""#文档字符串 x = 'abc'#类属性 def foo(self):#类属性foo,也是方法 return 'myclass'
类对象及类属性
实例化
a = MyClass #实例化
__init__方法
class MyCalss: def __init__(self):#初始化 print('init') a = MyCalss()
实例对象
self
class Person: def __init__(self): print(id(self)) c = Person() #会调用__init__ print('p={}'.format(id(c))) #输出结果: 43079160 c=43079160
实例变量和类变量
class Person: age = 7 height = 175 def __init__(self,name,age=23): self.name = name self.age = age tom = Person('tom') jerry = Person('jerry',20) Person.age = 30 print(Person.age,tom.age,jerry.age) print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n') Person.height += 5 print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n') tom.height = 176 print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n') Person.weight = 65 print(Person.__dict__['weight']) print(tom.__dict__['weight'])#KeyError
装饰一个类
#增加类变量 def add_name(name,cls): cls.NAME = name #动态增加类属性 #改进成装饰器(带参) def add_name1(name): def wrapper(cls): cls.NAME = name return cls return wrapper @add_name1('tom') class Person: AGE = 1 print(Person.NAME)
类方法和静态方法
普通函数
类方法
静态方法
方法的调用
class Person: def normal_method(): print('nomal') def method(self): print("{}'s method ".format(self)) @classmethod def class_method(cls): print('class = {0.__name__} {0}'.format(cls)) cls.HEIGHT =175 @staticmethod def static_method(): print(Person.HEIGHT) #~~~类访问~~~ print(1,Person.normal_method()) # print(2,Person.method())#报错 print(3,Person.class_method()) print(4,Person.static_method()) #~~~实例访问~~~ tom = Person() # print(5,tom.normal_method())#报错 print(6,tom.method()) print(7,tom.class_method()) print(8,tom.static_method())
访问控制
私有属性Private
一般来说,可以在内部自定义一个方法来访问私有变量。
私有变量的本质
保护变量
私有方法
私有方法的本质
私有成员的总结

更多精彩