Skip to content

[Python learning] Object and Class

Gukie edited this page Dec 19, 2017 · 2 revisions
    1. default inherit from Object
    1. attributes will be defined in constructor
    1. every method in class, will have a parameter named 'self', which is the reference of object invoke current method.
    1. default, the attribute/method will be public, to make it private, add 2 underscore character in prefix.

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()

How to use:

from Car import *

car1 = Car(4115.455)
car1.display()

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

Clone this wiki locally