gx.ct10000,2014133,4567a
class person(object): def __init__(self, name, age): self.name = name # 实例变量 self.age = age # 实例变量 p1 = person("tom", 18) print(p1.name) # tom 访问实例变量 p1.name = "andy" # 修改实例变量的值 print(p1.name) # andy
class foo(object): count = 0 # 类变量 def __init__(self): foo.count += 1 print(foo.count) # 0 访问类变量 foo() foo() foo() print(foo.count) # 3
class user(object): def login(self): # 实例方法 print("欢迎登录") u = user() u.login() # 调用实例方法
语法:
@classmethod def 方法名(cls): pass
class foo(object): @classmethod def add(cls, a, b): # 类方法 print(cls) return a + b print(foo) print(foo.add(1, 2)) 结果: <class '__main__.foo'> <class '__main__.foo'> 3
语法:
@staticmethod def 方法名.(): pass
class foo(object): @staticmethod def welcome(): print("---welcoming---") foo.welcome() # ---welcoming---
在python中使用__作为方法或者变量的前缀,那么这个方法或者变量就是一个私有的
如果类中存在继承关系,子类是无法继承父类的私有内容的
class person(object): def __init__(self, salary): self.__salary = salary def sal(self): print(self.__salary) p1 = person(50000) print(p1.__salary) # 报错 p1.sal() # 50000
class person(object): def __init__(self, name, salary): self.name = name self.__salary = salary def __sal(self): print(self.__salary) def display(self): self.__sal() p1 = person("tom", 50000) p1.display() # 50000
注意:
class person(object): def __init__(self, name, birthday): self.name = name self.birthday = birthday @property def age(self): return 2018 - self.birthday p = person("tom", 1994) print(p.age) # 24
增加方法,使之可以赋值:
class test(object): def __init__(self): self.__num = 100 @property def num(self): return self.__num @num.setter def num(self, new_num): self.__num = new_num t = test() print(t.num) # 100 t.num = 50 print(t.num) # 50
property另一种表达方式:
property(fget=none, fset=none, fdel=none, doc=none)
class test(object): def __init__(self): self.__num = 100 def getnum(self): return self.__num def setnum(self, new_num): self.__num = new_num num = property(getnum, setnum) p1 = test() print(p1.num) # 100 p1.num = 50 print(p1.num) # 50
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论