>>> class class_demo(object):#定义一个空类,继承自python中最大的基类object
... pass
...
>>> c = class_demo()
>>> print(type(c))
<class '__main__.class_demo'>
>>> c.name = 'root' #绑定变量
>>> print(c.name)
root
>>> c.pwd = 'root' #绑定变量
>>> print(c.pwd)
root
相当与c++中的构造函数,对类进行初始化工作,在对象创建时被调用
>>> class user_info(object):
... def __init__(self, name, pwd, salary, money):
... self.name = name
... self.pwd = pwd
... self.salary = salary
... self.money = money
...
>>> user = user_info('root', 'root', 5000, 500)
>>> user.name
'root'
>>> user.pwd
'root'
>>> user.salary
5000
>>> user.money
500
>>> class user_info(object):
... def __init__(self, name, pwd, salary, money):
... self.name = name
... self.pwd = pwd
... self.salary = salary
... self.money = money
...
... def print(self):
... print("Name:%s Salary:%d Money:%d" % (self.name, self.salary, self.money))
...
>>> user = user_info('root', 'root', 5000, 500)
>>> user.name
'root'
>>> user.pwd
'root'
>>> user.salary
5000
>>> user.money
500
>>> user.print()
Name:root Salary:5000 Money:500
在类的变量前边加上两个下划线 表示该变量只在类的内部访问
>>> class user_info(object):
... def __init__(self, name, pwd, salary, money):
... self.name = name
... self.__pwd = pwd
... self.salary = salary
... self.__money = money
...
... def print(self):
... print("Name:%s Salary:%d Money:%d" % (self.name, self.salary, self.__money))
...
>>> user = user_info('root', 'root', 5000, 500)
>>> user.name
'root'
>>> user.__pwd
Traceback (most recent call last):
File "" , line 1, in
AttributeError: 'user_info' object has no attribute '__pwd'
>>> user.salary
5000
>>> user.__money
Traceback (most recent call last):
File "" , line 1, in
AttributeError: 'user_info' object has no attribute '__money'
>>> user.print()
Name:root Salary:5000 Money:500
#python中的权限访问做的并不是特别严谨,需要程序员自觉遵守,可以通过下面这种方式访问到
#可以提供get 和set 这些接口来访问
>>> user._user_info__pwd
'root'
>>> user._user_info__money
500
python中最大的基类 object
>>> # animal类继承自object
... class animal(object):
... def eat(self):
... print("Animal eat...")
...
... pass
...
... # pig类继承自animal, 也拥有object的东西
>>> class pig(animal):
... pass
...
... # dog类继承自animal, 也拥有object的东西
>>> class dog(animal):
... # 重写eat
... def eat(self):
... print("Dog eat ")
... pass
...
>>> def main():
... xx = pig()
... xx.eat()
... zz = dog()
... zz.eat()
...
>>> main()
Animal eat...
Dog eat