#!/usr/bin/python3
class Dog:
name = "haha"
def eat(self):
return "eat food"
# 实例化类
x = Dog()
# 访问类的属性和方法
print("Dog 类的属性 name 为:", x.name)
print("Dog 类的方法 eat 输出为:", x.eat())
结果:
Dog 类的属性 name 为: haha
Dog 类的方法 eat 输出为: eat food
#!usr/bin/python3
class Dog:
name = "haha10"
def __init__(self,name):
self.name = name
x = Dog("12345")
print("name = ", x.name)
结果:
name = 12345
17.3 私有属性访问私有属性会报错
#!/usr/bin/python3
class people:
# 定义私有属性,私有属性在类外部无法直接进行访问
__name = "zhangsan"
# 实例化类
p = people()
print("name = ", p.__name)#这里会报错
结果:
Traceback (most recent call last):
File "/Users/bytedance/source/builder/builder/handler/test.py", line 10, in
print("name = ", p.__name)
AttributeError: 'people' object has no attribute '__name'
与私有属性一样,私有方法也不能在外部访问,定义私有方法也是在方法名前面加__,在外部调用私有方法会报错
#!usr/bin/python3
class student():
def __get_name(self):
print("student")
x = student()
x.__get_name() #这行会报错
结果:
Traceback (most recent call last):
File "/Users/bytedance/source/builder/builder/handler/test.py", line 7, in
x.__get_name() #这行会报错
AttributeError: 'student' object has no attribute '__get_name'
与java一样,Python 同样支持类的继承
#!/usr/bin/python3
class people:
def get_name(self):
print("我叫张三")
class student(people):
pass
s = student()
s.get_name()
结果:
我叫张三
17.6 方法重写#!usr/bin/python3
class people:
def get_name(self):
print("wo shi zhangsan10")
class student(people):
def get_name(self):
print("hahahaha")
x = student()
x.get_name()
结果:
hahahaha



