Python Classes and Inheritance

Python Classes and Inheritance

一、User Define Class

1. Adding Parameters to the Constructor

For example,when we create new points, we supply the x and y coordinates as parameters. When the point is created, the values of initX and initY are assigned to the state of the object, in the instance variables x and y.

This is a common thing to do in the init method for a class: take in some parameters and save them as instance variables.

So in this way, a useful function which can be define in our own class only one time is constructor.Constructor is defined with a method called ‘init’,just like the instance below.

class Point:
    """ Point class for representing and manipulating x,y coordinates. """

    def __init__(self, initX, initY):

        self.x = initX
        self.y = initY

p = Point(7,6)

2.Adding other function to class

First, we should know what the class is.In my own opinion, class is a independent program module which is nearly the same as main program, just like classes in C#.
So, defining different functions in class should has a special label to show that it can invoke the parameter belong to this class.‘self’ can do this, just like code should below.

class Point:
    """ Point class for representing and manipulating x,y coordinates. """

    def __init__(self, initX, initY):

        self.x = initX
        self.y = initY

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def distanceFromOrigin(self):
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

tips:
class is just a kind of data objects, so it can also be evaluated to a param, and it can also be given to a function as a input param.

3. Comprehension with ‘self’

Self can be treated as a bridge between both inner class and outer class, if a param want to be invoked outside the class, it should be ‘public’ just like self expressed.And if a param can be used in different function of a class,it should bee also define by self.

tips:so what can be program independently instantiate a class is the function has double underscore such as “__ init __”.

二、Inheritance

1.Method of define a class which inheritant other class

So, at first, we should know what the inheritance is.

2.Method of override function or construction in classes

If a method is defined for a class, and also defined for its parent class, the subclass’ method is called and not the parent’s. This follows from the rules for looking up attributes that you saw in the previous section.

We can use the same idea to understand overriding methods.

Let’s return to our idea of making Cats, Dogs, and other pets generate a string for their “mood” differently.

Here’s the original Pet class again.

from random import randrange


class Pet():
    boredom_decrement = 4
    hunger_decrement = 6
    boredom_threshold = 5
    hunger_threshold = 10
    sounds = ['Mrrp']
    def __init__(self, name = "Kitty"):
        self.name = name
        self.hunger = randrange(self.hunger_threshold)
        self.boredom = randrange(self.boredom_threshold)
        self.sounds = self.sounds[:]  # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class

    def clock_tick(self):
        self.boredom += 1
        self.hunger += 1

    def mood(self):
        if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold:
            return "happy"
        elif self.hunger > self.hunger_threshold:
            return "hungry"
        else:
            return "bored"

    def __str__(self):
        state = "     I'm " + self.name + ". "
        state += " I feel " + self.mood() + ". "
        # state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds)
        return state

    def hi(self):
        print(self.sounds[randrange(len(self.sounds))])
        self.reduce_boredom()

    def teach(self, word):
        self.sounds.append(word)
        self.reduce_boredom()

    def feed(self):
        self.reduce_hunger()

    def reduce_hunger(self):
        self.hunger = max(0, self.hunger - self.hunger_decrement)

    def reduce_boredom(self):
        self.boredom = max(0, self.boredom - self.boredom_decrement)

Meanwhile maybe someone confuse with why construction function can hold another function inner it, we should treat it as the code inner the second function has been taken into the first function directly.

Tips: If we want to invoke the function in its own class, we should use ‘self.’ as the prefix, instead of using it directly.

三、Test Case

1.Test is a module of python

Test has a lot of function belong to it, such as testEqual, it can be use as test.testEqual(object_1, object_2), and return pass or failed. The type of objects can be int float string char and so on, class is also acceptable.

import test
x,y=1,2
test.testEqual(x,y)

it’ll return pass if the value is “True”, meanwhile it’ll return “Exception…”.
Tips:so with the help of test, we can write code without frequent debug.
In my own opinion, test’s module’s main workplace is Black-Box Testing.
Especial a long complicated and protected code mode.

2.assert function

Assert is function of python which is used to judge the correction of the program we set into, if the return value is “true”----boolean, run pass, else it will determine our program and avoid the bigger mistake.


x,y=1,2
assert x==y

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值