Old new class, private methods, class attributes and class methods, static methods - Python Object Oriented

  1) new class (recommended): When you define a class, class behind brackets should inherit the base class (object). In python3.x if the parent class is not specified, the default is used as a base class object; in python2.x, if the parent class is not specified, then the object is not to as the base class.

  2) old-style class (Classic): When you define a class, class behind brackets do not inherit the object class, even without parentheses.

  3) dir built-in method is used to view the class.

Second, private methods and properties

  1) the object is a private property undesirable properties disclosed; private method is a method disclosed subject did not want. When you define private properties and methods, before the property or method name to add __ (two underscores)

# Define a class man


class Man(object):

  def __init__(self,name,age):


      self.name = name

      self .__ age = age # defines a private attribute age

  def __secret(self):

      print "% s of age is:% s"% (self.name, self .__ age)


  def test (self): # public class can call private property and private methods


      self.__secret()

demo = Man('demo',18)

# Can not access private property

# print demo.age

# Can not access private methods

# demo.secret()

demo.test()

2) inherit private property and private methods in question: a subclass can not inherit private property and private methods of the parent class

class A(object):

  def __init__self(self,name):

      self .__ age = 18 # define a private and public property attribute

      self.name = name

  def __secret(self):

      print "% s of age is% s"% (self.name, self .__ age)

class B(A):


  def test(self):

      print self.name

      # Can not access private properties and methods of the parent class


      # print self.__age 

      # self.__secret()

demo = A('demo')

# In the outside world do not have access to private properties and methods of the parent class

demo.test 

Third, the class attributes and class methods

  1) class object: class is a special object, also known as class objects. It is also an object class attributes and their corresponding methods, properties and class method called a class.


  2) class properties: a class object is defined properties; commonly used to record associated with the class characteristic; does not record the characteristics of the particular object. Defined under the class keyword.

  3) class methods: Method for the class object definition; within the class methods can invoke only class attribute or a class method. Defined format: @classmethod def class name (): pass 

 class Toy(object):

  count = 0 # Use an assignment statement to define the class attribute


  def __init__(self,name):

      self.name = name

      Toy.count + = 1 # each time an object is created, the counter is incremented by 1


  Identifying a class method defined @classmethod #


  def show_toy_count(cls):

      print "the number of toys subject to% d"% cls.count


# Create a toy objects

toy1 = Toy ( 'LEGO')


toy2 = Toy ( 'toy car')

Toy.count # call the class attribute


Toy.show_toy_count () # call the class method

Fourth, the static method

  1) static method: at the time of development, if necessary in a method of encapsulating class; This method does not require access to the instance attributes or instance method, or class attribute does not require access to the class method; this point we can encapsulate a static method method. Defined format: @staticmethod def class name (): pass 

class Cat(object): 

    @staticmethod

    # Can not access the instance attribute / property class

    # Static methods do not need to pass the first parameter self


    def  call():

        print "meow meow meow ~ ~ ~"


By # to call 'static methods class name.'; (Does not need to create an object you can directly call the static method)

Cat.call()   

Fifth, a comprehensive class instance objects, classes, attributes, static methods 

  1) Requirements: a game design class


    Properties: define a property record high points top_score record game (class attributes)
          to define a property player_name record current player's name gamers (Instance Properties)
    method:
          show_help displays the game help information (static methods, their parameters)
          show_top_socre display a record high points (class methods, parameters CLS)
          start_game start of the current players of the game (instance method, the parameter for the self)

import random


Game class (Object):
    top_score = 0 # define a class attribute, the highest score is calculated
    DEF the __init __ (Self, name):
        self.play_name name =
        Game.top_score # = 0 is initialized to 0
    @staticmethod
    DEF show_help (): # define the static function
        print "game help"
        print "randomly generated numbers 1-10 three guesses first guessed 10 points;.! the second guessed 5 points, 3 points for the third time guess;! 0 guess guess not finished after that, you will record the highest score! "

    def start_game (self): # define an instance method
        NUM = the random.randint (. 1, 10)
        Score = 0
        for I in Range (. 3):
            Guest = int (the raw_input ( "Please enter a number to guess:"))
            IF = Guest NUM =:
                IF I == 0:
                    score = 10 +
                    BREAK
                elif I ==. 1:
                    score + =. 5
                    BREAK
                the else:
                    score + =. 3
                    BREAK
            the else:
                score = 0
        Print "Xiaoming score of D%"% score
        IF score > Game.top_score:
            Game.top_score Score =


    @classmethod   
    DEF show_top_socre (CLS): # Create a class method, display game scores highest
        print "displays the highest score:% s"% cls.top_score

# View Game Help

Game.show_help()

 # Create Object games

xming = Game ( 'Hsiao Ming')

# Start playing

xming.start_game()

# View historical high points

Game.show_top_socre ()
 
examples Summary:

1, examples of method: The method requires internal access to the instance attribute.

2, class methods: Method inside 'only' access class properties

3, the static method: internal method, no need to access class instance attributes and properties

4, the internal method requires both instance properties, there is a need to access the class properties, it can be defined as an instance method

Guess you like

Origin www.linuxidc.com/Linux/2020-02/162275.htm