@property
属性装饰器
class Person:
def __init__(self,name):
self.__name = name
@property
def info(self):
return self.__name
>>> p = Person("tom")
>>> print(p.info)
tom
直接按照调用属性的方法进行调用即可
只读属性!
读写属性
class Person:
def __init__(self,name):
self.__name = name
@property
def info(self):
return self.__name
@info.setter
def info(self,val):
self.__name = value
@info.getter
def info(self):
return self.__name
@info.deleter
def info(self):
del self.__name
p = Person("Bob") #是我们常说的B,来自网络安全课
p.name = "Alice" #是我们常说的A
print(p.info)
属性构造器指定setter getter
class Person:
def __init__(self,name):
self.__name = name
def getName(self):
return self.__name
def setName(self,value):
self.__name = value
def delName(self):
del self.__name
name = property(getName,setName,delName,"我是name属性")
p = Person("Bob")
print(p.name)
自定义属性
class C1:
pass
o = C1();
o.name = "Alice"
print(o.name)
结果:
Alice
======================================================
字典方式:
class C1:
pass
o = C1();
o.name = "Alice"
print(o.__dict__)
结果:
{'name': 'Alice'}
这样的属性是共有的
想定义私有的属性,用到Object的类的方法
设置属性
__getattr__ #优先级高
__getattribute__ #优先级低
__setattr__
__delattr__
实例方法
def 方法名称 (self,[参数列表])
class Person:
def say_hi(self,name):
self.name = name
print("I am ",self.name )
o = Person();
o.say_hi("Alice")
结果:
I am Alice
不需要传入 self
静态方法
@staticmethod
def 方法名 ([参数列表]):
不用self 实例方法必须要self
class Person:
@staticmethod
def info(c):
return c
print(Person.info(3))
3
直接用类名进行调用
类方法
不对特定实例进行操作,在定义的时候有区别
@classmethod
def 方法名 (cls,[参数列表])
调用时不需要对cls进行传参数
用类名调用
class Foo:
classname = "Foo"
def __init__(self,name):
self.name = name
def f1(self):
print(self.name)
@staticmethod
def f2():
print("static")
@classmethod
def f3(cls):
print(cls.classname)
f = Foo("zhong")
f.f1()
Foo.f2()
Foo.f3()
zhong
static
Foo
类的方法
class Methods:
def publicMethod(self):
print("共有方法")
def __privateMethod(self):
print("私有方法")
def publicMethod2(self):
self.__privateMethod()
m = Methods();
m.publicMethod()
m._Methods__privateMethod()
共有方法
私有方法
类名调用共有方法要传入一个对象
class Methods:
def publicMethod(self):
print("共有方法")
def __privateMethod(self):
print("私有方法")
def publicMethod2(self):
self.__privateMethod()
m = Methods();
Methods.publicMethod(m)
#私有的方法调用也要传入一个对象
Methods._Methods__privateMethod(m)
方法重载
看法不一致
1.有重载
class Person:
def say_hi(self,name):
print("hello I am " ,self.name)
def say_hi(self,name,age):
print("hello I am{0} age{1}",format(name,age))
2.没有重载的原因:
class Person:
def say_hi(self,name):
print("hello I am " ,self.name)
def say_hi(self,name,age):
print('hello I am {0}, age {1}'.format(name,age))
p = Person()
p.say_hi('Tom',23)
p.say_hi('Tom')
hello I am Tom, age 23
Traceback (most recent call last):
File "D:/Program Files/Python36/test.py", line 9, in
p.say_hi('Tom')
TypeError: say_hi() missing 1 required positional argument: 'age'
后面的函数会对之前的函数进行覆盖
继承
python 里面的继承是多继承
java里:extends
python里面:
class 子类 ( 父类1,父类2,父类3,.........)
Eg:
class Person(object)