【Python】类变量的作用域

回顾下python类的继承。

一种是初始化的时候就创建self.age 类变量。类里的其他方法都可以使用self.age。

如果不加self,在本类的其他方法中是不能使用的。

第一种,直接__init__内初始化类变量。

class Person:
    def __init__(self,name, age):
        self.name = name
        self.__age = age

    def __test(self):
        print("这是父类的私有方法")

    def test(self):
        self.__test()
        print("这是父类的公有方法")

    # def setAge(self,age):
    #     self.__age = age

    def getAge(self):
        return self.__age



class Student(Person):
    def __init__(self,school,name,age):
        super(Student, self).__init__(name=name,age=age)
        self.school = school
    def stuTest(self):
        super().test()
        print("所在学校为:",self.school)

stu = Student("一中","tom",12)
stu.stuTest()

print('1'*20)
print("学生的姓名是:",stu.name)
#
# print('2'*20)
# print("学生的年龄是:",stu.setAge(15))

print('3'*20)
print("学生的年龄是:",stu.getAge())

运行结果

这是父类的私有方法
这是父类的公有方法
所在学校为: 一中
11111111111111111111
学生的姓名是: tom
33333333333333333333
学生的年龄是: 12

Process finished with exit code 0

第二种,使用setAge()方法设置年龄。

需要注意的是,Person / Student 的__init__(self,name)都删除了age。

调用setAge(self,age)方法,设置self.age的值。

这样的好处在于,可以在setAge()方法里写异常处理,使得程序更加健壮。

class Person:
    def __init__(self,name):
        self.name = name
        # self.__age = age

    def __test(self):
        print("这是父类的私有方法")

    def test(self):
        self.__test()
        print("这是父类的公有方法")

    def setAge(self,age):
        self.__age = age

    def getAge(self):
        return self.__age



class Student(Person):
    def __init__(self,school,name):
        super(Student, self).__init__(name=name)
        self.school = school
    def stuTest(self):
        super().test()
        print("所在学校为:",self.school)

stu = Student("一中","tom")
stu.stuTest()

print('1'*20)
print("学生的姓名是:",stu.name)

print('2'*20)
print("学生的年龄是:",stu.setAge(15))

print('3'*20)
print("学生的年龄是:",stu.getAge())

运行结果

这是父类的私有方法
这是父类的公有方法
所在学校为: 一中
11111111111111111111
学生的姓名是: tom
22222222222222222222
学生的年龄是: None
33333333333333333333
学生的年龄是: 15

Process finished with exit code 0

特特特别重要的是,在一个类里,不用self声明的变量,是不能在本类中其他方法里使用的。

错误的

正确的

class Person:
    def __init__(self, name):
        self.name = name
        self.age = self.set_age(19)

    def set_age(self, age):
        print("get_age name:{}".format(self.name))
        try:
            if age<50:
                raise SyntaxError
            else:
                self.age = age
                print("set_age: ", self.age)
        except Exception as err:
            print("err:", err)

    def show(self):
        print("show_age: ", self.age)


if __name__ == '__main__':
    p1 = Person("John")
    print("p1.name: ", p1.name)

    print('-'*20)

    p1.set_age(26)
    p1.show()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值