class Person: def __init__(self,name,gender,hobby): self.name = name # 实例变量 对象里的变量 self.gender = gender self.hobby = hobby s = Person('张三','男','打篮球') print(s.hobby) s.hobby = '踢足球' print(s.hobby)
二、类变量:变量属于类,可是对象也能够访问 ide
class Person: country = '中国' def __init__(self,name,gender): self.name = name self.gender = gender c = Person('Ann','女') b = Person('Bob','男') print(Person.country) c.country = '大清' # 大坑,没有修改类变量 print(c.country) # 类变量能够给对象使用 print(b.country)
class Computer: #实例方法(成员方法) def play(self): print('电脑能够玩游戏') # 在定义实例方法的时候,必须给出一个参数self # 形参的第一个参数,自动的把对象给传递进来 def work(self): # self是当前类的对象 print(self) print('电脑能够用来工做') c = Computer() c.work() # 调用的时候不须要手动的给出self print(c)
class Person: # 实例方法 def eat(self): print('吃遍山珍海味') @classmethod # 装饰器,此时这个方法是一个类方法 def talk(cls): # 此时接收到的cls是类名 print('自言自语') # # 用对象访问 # s = Person() # s.talk() # 在调用类方法的时候,默认的把类名传递给类方法 # print(Person) # 类方法通常用类名访问 Person.talk() # 类方法
class Quit: @staticmethod def meet(): print('会议保持安静') # 静态方法可使用对象访问,也可使用类名访问,可是通常推荐使用类名访问 c = Quit() c.meet() # 推荐使用类名访问 Quit.meet()
class Person: __qie = 'beauty' def __init(self,name,secret): self.name = name self.__secret = secret # 私有内容 实例变量 def tell(self): print(f"你的秘密是{self.__secret}") print(Person.__qie) # 私有的类变量只能在类中调用 return self.__secret def __dream(self): # 私有的实例方法 print('个人梦想是..') @staticmethod def __think(): print('当心思') @classmethod def __work(cls): print('我的工做') p =Person('zhangmeng','过去的生活') # print(p.__secret) # 私有的内容只能在类中调用 # # p.tell() # print(Person.__qie) # p.__dream() # Person.__work()
class Person: def __init__(self,name,hobby,birth): self.name = name self.hobby = hobby self.birth = birth # 年龄应该是算出来的,而不是直接存储 @property # 把一个方法更改为一个属性,每次拿属性的时候都会自动的去执行这个方法 # 方法的返回值就是属性值 def age(self): # 实例方法 print('个人年龄') return 2018 - self.birth c = Person('zhangmeng','dance',1999) # c.age print(c.age) # 看着像一个变量同样使用,实际上这里是调用的一个方法 # c.age = 26 # 不能够,由于age是一个方法,不是一个变量
class Person: __qie = 'beauty' def __init(self,name,secret): self.name = name self.__secret = secret # 私有内容 实例变量 def tell(self): print(f"你的秘密是{self.__secret}") print(Person.__qie) # 私有的类变量只能在类中调用 return self.__secret def __dream(self): # 私有的实例方法 print('个人梦想是..') @staticmethod def __think(): print('当心思') @classmethod def __work(cls): print('我的工做') p =Person('zhangmeng','过去的生活') # print(p.__secret) # 私有的内容只能在类中调用 # # p.tell() # print(Person.__qie) # p.__dream() # Person.__work()