Know Python object-oriented?

Problem Scenario

Wang is the newly recruited staff of a game company, one day, he was handed over to the head of a task to design some personas as a prospective forthcoming development of a game, including a variety of occupations, such as priests, warriors and mages and many more. Each job has some of its own unique attributes and skills, but there will be some common attributes and methods. Assuming this company is Pythonto develop the game.

Experienced object-oriented programming learning of Wang quickly clarified the thinking, this kind of thinking needed to design. Because of these occupations will have some common properties and methods should obviously be the common attributes and methods of these professions out as a public class, and this class is called common base class, otherwise known as the parent class; other occupations may be based on the class to increase public properties and methods, these occupations is called the subclass. After that is the object-oriented inheritance coding ideas, clarify design ideas, Wang immediately started working to implement the corresponding code.


Parent class design

First, for each game character, it will have a name and gender attributes. Wang leader also told that we can not let other people know how our role is to design, as well as what are the attributes, how should this design? Smart Wang immediately thought of the idea of ​​the package, through the property and the implementation details hidden object class can prevent external call properties directly or modify the properties. Therefore, Wang immediately write the following code:

class Roler(object):
    """
    用户角色类,需要隐藏属性
    Args:
        __username: 用户名,string
        __sex:性别, string
    """
    def __init__(self, name=None, sex="male"):
        self.__username = name
        self.__sex = sex
        self.__hp = 1000

    def get_username(self):
        # 获取用户名
        return self.__username

    def get_sex(self):
        # 获取用户性别
        return self.__sex

    def add_hp(self, hpr):
        # 角色可以回血
        self.__hp += hpr

    def __repr__(self):
        # 打印对象信息
        return "username : {0}\nsex : {1}\nhp : {2}".format(self.__username, self.__sex, self.__hp)

Different from Javaand C++, in the Pythonmiddle is not privatesuch as keywords. So how do we define a class of property is private it? The method is in front of the class name attribute plus two underscores, it means that as a __usernameform, which is the definition of private property in the way. The reason is because Pythonthe inside of the class, starting all double underlined name will be replaced by a single underline and increase the class name of fashion. In essence, __usernameit was replaced with _Roler__usernamea form of.

role1 = Roler("weisheng", "male") # 建立一个新角色
print(role1) # 打印该角色的信息,调用 __repr__() 方法

print(role1.__username) # AttributeError,该属性是私有的
print(role1._Roler__username) # weisheng,可以打印

Subclass Design

With the parent class is not enough, because each job will have some of its unique properties and methods. So, for each job, we also need to implement a class. Wang first pastor for the profession to achieve, as a pastor law of the medical profession, first affirmed the need for a MPvalue. At the same time, it can give other users restore the value of life. Therefore, in the following ways to achieve the priest class:

class Pastor(Roler):
    """
    牧师类,继承自用户角色类
    Args:
        __MP: 魔法值
    """
    def __init__(self, name, sex):
        # 调用父类的构造函数
        super().__init__(name, sex)
        self.__mp = 100
    def get_mp(self):
        return self.__mp
    def __repr__(self):
        return super().__repr__() + "\nmp : {0}".format(self.__mp)

    def fullhealth(self, other):
        # 技能1:回复其它用户生命值
        other.add_hp(200)

The priest class definition, first call the parent class constructor to initialize the user's name, gender, hp value. At the same time, there is a priest mp value of this property is unique to the profession (Do not be investigated for details). With the addition of the appropriate attributes, __repr__()methods need to be rewritten, you can call the parent class __repr__()plus the unique properties of the priest class method.

Subclass can not directly call the private property of the parent class, so for some of the private property of the parent class, you need to call the method through.

There is also a pastor skill, he can give back to the blood of other user roles, you need to practice a fullhealth()method parameter is the role of other classes. Test case as follows:

pastor1 = Pastor("ergouzi", "male") # 建立一个牧师职业
print(pastor1)  # 打印该职业角色的信息

pastor1.fullhealth(role1)  # 牧师可以给其他角色回血
print(role1)  # 可以发现该用户的 hp 值发生变化

Other occupations may reference design features of the profession to make corresponding design, do not here in the description.


Object-oriented summary

By following the game character Wang's design, I believe you have to Pythonhave some understanding of the object-oriented programming. Object-oriented programming is now commonly used in a programming mode, it is with respect to the process-oriented programming. Object-oriented programming object as the basic unit of the program, an object contains function data and operational data. The idea of the three most important feature is encapsulation, inheritance and polymorphism, in fact, these characteristics are reflected in the above example, you can find it?

Although the above examples have been set forth most of the ideas of object-oriented programming, but also the first time I went to the design of the relationship between these classes, so each example is very simple, there may also be problems in design thinking, please forgive me.

All Code please visit: Object-Oriented Programming

More exciting content will be released in the number of public iced coffee with a dog , or search for the Micro Signal icedcoffee7 add public number.

Guess you like

Origin www.cnblogs.com/ydcode/p/10985993.html