Discuss / Python / 一点体会

一点体会

Topic source
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Person(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def func(self):
        print(self.__name)


class Student(Person):
    def func1(self):
        print(self.__name)
    pass


bart = Student('bart',100)
bart.func1()

返回错误:
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    bart.func1()
  File "C:\Users\Administrator\Desktop\xxd.py", line 14, in func1
    print(self.__name)
AttributeError: 'Student' object has no attribute '_Student__name'

类Student继承了Person,但是一旦在父类中定义了私有变量,这个私有变量比如self.__name
只能在这个父类里面调用,即便是子类继承了父类,也不可直接调用,你可以试一下dir(bart)
发现没有_Student__name,只有_Person__name。但是如果你在父类中定义的是公共的属性,则
在子类,还有在外部可以调用。

多谢~!

perfect 一个类的私有变量只能在该类被调用,但是,在别的类可以通过调用父类的函数来使用父类的私有变量

class Person(object):

def __init__(self,name,score):
    self.__name = name
    self.__score = score
def func(self):
    print(self.__name)
def get_name(self):
    return self.__name

class Student(Person): def func1(self): print(self.get_name()) pass

bart = Student('bart',100) bart.func1()

bart


  • 1

Reply