Python编程_Lesson015_类的基础用法

和其它高级语言一样,Python也有类将数据和函数有效的组合起来。

类的定义

class UserInfo(object):
    pass
type(UserInfo)
<class 'type'>

type(UserInfo)
<class 'type'>
type(list)
<class 'type'>

这样我们就定义了一个空类,查看它的类型也是class,和其它的list、dict等类型一样。

给类对象绑定属性
class UserInfo(object):
    pass
user_info = UserInfo()
user_info.name = "root"
user_info.name
'root'
user_info.password = "root"
user_info.password
'root'

我们成功的给user_info这个对象绑定了username和password两个属性。
但是我们绑定的这两个属性只存在于user_info这个对象,它们并不属于UserInfo()这个类,我们来检验一下

class UserInfo(object):
    pass
user_info = UserInfo()
user_info.name = "root"
user_info.name
'root'
user_info.password = "root"
user_info.password
'root'
user_info2 = UserInfo()
user_info2.username
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'UserInfo' object has no attribute 'username'
user_info2.password
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'UserInfo' object has no attribute 'password'

我们可以看到user_info2这个对象并没有username和password这两个属性。
看到这里,我们就会这样想,有没有办法让这个UserInfo类在定义的时候就有一些属性呢?答案是肯定的。

类属性的绑定

我们使用基类的__init__()函数进行类属性的绑定,它相当于其它高级编程语言的构造函数,从这里看应该是初始化函数。

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.username = username
        self.password = password
        self.salary = salary
        self.balance = balance

user_info_1 = UserInfo("root", "root", 3000, 2000)
user_info_1.username
'root'
user_info_1.username
'root'
user_info_1.salary
3000
user_info_1.balance
2000

这样我们就成功的给UserInfo这个类绑定了username、password、salary和balance这四个属性并且可以访问了。
需要注意的是:__init__函数的第一个参数无论如何都是self,否则是无法进行绑定的,因为不知道绑定到哪里!!!在生成对象的时候,必须要传递四个参数,否则也是生成不成功的!!!
虽然这样能够对类属性进行一个一个的输出,但是我们能不能让这个类自己输出所有的属性的,也是可以的。

类方法和属性的绑定(类属性是共有的)

为了方便,我们改成pycharm IDE来进行编写!

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.username = username
        self.password = password
        self.salary = salary
        self.balance = balance

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d" %(self.username, self.password, self.salary, self.balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    user_info_1.print()
    user_info_1.salary = 10
    user_info_1.print()


if __name__ == "__main__":
    main()

打印结果如下:

User Name:root Password:root Salary:3000 Balance:1600
User Name:root Password:root Salary:10 Balance:1600

从结果上我们会发现一个问题,我们的月工资竟然被随随便便的更改了!!!
可不可以不被更改呢?
当然也是可以的!!!将类属性变为私有即可,但是这种方法也不是绝对的,因为在Python中没有绝对的私有属性。

类方法和属性的绑定(类属性是共有的)
class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.__username = username
        self.__password = password
        self.__salary = salary
        self.__balance = balance

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d"
              % (self.__username, self.__password, self.__salary, self.__balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    user_info_1.print()
    user_info_1.salary = 10
    user_info_1.print()


if __name__ == "__main__":
    main()

打印结果如下:

User Name:root Password:root Salary:3000 Balance:1600
User Name:root Password:root Salary:3000 Balance:1600

这次没有被修改。但是我们也没有办法访问某一个属性和修改某一个属性了,那又该如何呢???
我们可以使用setter和getter解决。

如下所示:

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.__username = username
        self.__password = password
        self.__salary = salary
        self.__balance = balance

    def get_username(self):
        return self.__username

    def get_password(self):
        return self.__password

    def get_salary(self):
        return self.__salary

    def get_balance(self):
        return self.__balance

    def set_username(self, username):
        self.__username = username

    def set_password(self, password):
        self.__password = password

    def set_salary(self, salary):
        self.__salary = salary

    def set_balance(self, balance):
        self.__balance = balance

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d"
              % (self.__username, self.__password, self.__salary, self.__balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    user_info_1.print()
    user_info_1.set_username("admin")
    print(user_info_1.get_username())
    user_info_1.print()


if __name__ == "__main__":
    main()

结果如下:

User Name:root Password:root Salary:3000 Balance:1600
admin
User Name:admin Password:root Salary:3000 Balance:1600

成功的设置和访问了某一个属性。

我们还可以在设置属性的时候加上一些判断条件,满足条件,则可以修改,否则修改失败!

例如:
在设置之前,需要输入管理员密码,如果输入成功,则可以修改,否则将不能修改。

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.__username = username
        self.__password = password
        self.__salary = salary
        self.__balance = balance

    def get_username(self):
        return self.__username

    def get_password(self):
        return self.__password

    def get_salary(self):
        return self.__salary

    def get_balance(self):
        return self.__balance

    def set_username(self, username):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__username = username
        else:
            set_status = False

        return set_status

    def set_password(self, password):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__password = password
        else:
            set_status = False

        return set_status

    def set_salary(self, salary):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__salary = salary
        else:
            set_status = False

        return set_status

    def set_balance(self, balance):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__balance = balance
        else:
            set_status = False

        return set_status

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d"
              % (self.__username, self.__password, self.__salary, self.__balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    user_info_1.print()
    if user_info_1.set_username("admin"):
        print("set success!")
    else:
        print("set failed!")
    print(user_info_1.get_username())
    user_info_1.print()


if __name__ == "__main__":
    main()

结果如下

User Name:root Password:root Salary:3000 Balance:1600
Please input the super administrator password:123
set failed!
root
User Name:root Password:root Salary:3000 Balance:1600
类中的权限控制

Python类中的权限控制是非常弱的,尽管我们在属性前面加上了两个下划线,但是我们依然可以修改这个属性,请看下面的例子:

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.__username = username
        self.__password = password
        self.__salary = salary
        self.__balance = balance

    def get_username(self):
        return self.__username

    def get_password(self):
        return self.__password

    def get_salary(self):
        return self.__salary

    def get_balance(self):
        return self.__balance

    def set_username(self, username):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__username = username
        else:
            set_status = False

        return set_status

    def set_password(self, password):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__password = password
        else:
            set_status = False

        return set_status

    def set_salary(self, salary):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__salary = salary
        else:
            set_status = False

        return set_status

    def set_balance(self, balance):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__balance = balance
        else:
            set_status = False

        return set_status

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d"
              % (self.__username, self.__password, self.__salary, self.__balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    user_info_1.print()
    user_info_1._UserInfo__username = "admin"
    user_info_1.print()


if __name__ == "__main__":
    main()

结果如下:

User Name:root Password:root Salary:3000 Balance:1600
User Name:admin Password:root Salary:3000 Balance:1600

我们竟然这样修改了username的值,这充分说明Python中没有绝对的访问权限控制!


Python中的继承关系

class Animal(object):
    def eat(self):
        print("Animal eat...")


class Pig(Animal):
    pass


class Dog(Animal):
    pass


def main():
    aa = Pig()
    aa.eat()
    bb = Dog()
    bb.eat()


if __name__ == "__main__":
    main()

打印结果:

Animal eat...
Animal eat...

从结果可以看出,Pig类和Dog类都继承了父类Animal的eat方法,当然我们还可以对父类中的方法进行重写。
例如:

class Animal(object):
    def eat(self):
        print("Animal eat...")


class Pig(Animal):
    def eat(self):
        print("Pig eat...")


class Dog(Animal):
    pass


def main():
    pig = Pig()
    pig.eat()
    dog = Dog()
    dog.eat()


if __name__ == "__main__":
    main()

打印结果如下:

Pig eat...
Animal eat...

Pig类重写的eat方法被成功重写了!!!


基类object中的函数

在object类中有很多前面有两个下划线的函数,它们都具有一定的意义,比如:

_init_()’函数

init()’函数表示类在初始化的时候会被调用。

_len_()’函数

该函数是在调用len函数求可迭代对象的元素个数时候会被调用

class UserInfo(object):
    def __init__(self, username, password, salary, balance):
        self.__username = username
        self.__password = password
        self.__salary = salary
        self.__balance = balance

    def get_username(self):
        return self.__username

    def get_password(self):
        return self.__password

    def get_salary(self):
        return self.__salary

    def get_balance(self):
        return self.__balance

    def set_username(self, username):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__username = username
        else:
            set_status = False

        return set_status

    def set_password(self, password):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__password = password
        else:
            set_status = False

        return set_status

    def set_salary(self, salary):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__salary = salary
        else:
            set_status = False

        return set_status

    def set_balance(self, balance):
        set_status = True
        if input("Please input the super administrator password:") == "123456":
            self.__balance = balance
        else:
            set_status = False

        return set_status

    def __len__(self):
        print("len() is called!")
        return 0

    def print(self):
        print("User Name:%s Password:%s Salary:%d Balance:%d"
              % (self.__username, self.__password, self.__salary, self.__balance))


def main():
    user_info_1 = UserInfo("root", "root", 3000, 1600)
    len(user_info_1)


if __name__ == "__main__":
    main()

结果如下:

len() is called!
0

剩下的比如‘__abs__()’函数、‘__and__()’函数、‘__or__()’函数等等都也是这样的用法!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值