[Python learning] Object and Class - Gukie/machine-learning GitHub Wiki

  • default inherit from Object
  • attributes will be defined in constructor
  • every method in class, will have a parameter named 'self', which is the reference of object invoke current method.
  • default, the attribute/method will be public, to make it private, add 2 underscore character in prefix.
  • method name with leading and tailing 2 underscore is not private, it is public

Class definition

class Car:
    def __init__(self,price):
        self.price = price
        self.desc = "you deserve  it"
        self.__profit = price * 0.3 ## private attribute

    def display(self):
        print(self.desc,self.price)

    def __getProfit(self): # private method
        return self.__profit

    def showProfit2Boss(self):
        return self.__getProfit()

    def __notPrivate__(self): # this method is not private,  it is public
        print("not private")

How to use:

from Car import *

car1 = Car(4115.455)
car1.display()

profit = car1.showProfit2Boss()
print("Hi boss, this is our profit:",profit)