# Source: Class and Instance Variables# https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
class MyClass(object):# class variablemy_CLS_var = 10
# sets "init'ial" state to objects/instances, use self argumentdef __init__(self):# self usage => instance variable (per object)self.my_OBJ_var = 15
# also possible, class name is used => init class variableMyClass.my_CLS_var = 20
def run_example_func():# PRINTS 10 (class variable)print MyClass.my_CLS_var
# executes __init__ for obj1 instance# NOTE: __init__ changes class variable aboveobj1 = MyClass()
# PRINTS 15 (instance variable)print obj1.my_OBJ_var
# PRINTS 20 (class variable, changed value)print MyClass.my_CLS_var
run_example_func()
class MyClass:
def __init__(self):print('__init__ is the constructor for a class')
def __del__(self):print('__del__ is the destructor for a class')
def __enter__(self):print('__enter__ is for context manager')return self
def __exit__(self, exc_type, exc_value, traceback):print('__exit__ is for context manager')
def greeting(self):print('hello python')
if __name__ == '__main__':with MyClass() as mycls:mycls.greeting()
$ python3 class.objects_instantiation.py__init__ is the constructor for a class__enter__ is for context managerhello python__exit__ is for context manager__del__ is the destructor for a class
class Bill():def __init__(self,apples,figs,dates):self.apples = applesself.figs = figsself.dates = datesself.bill = apples + figs + datesprint ("Buy",self.apples,"apples", self.figs,"figsand",self.dates,"dates.Total fruitty bill is",self.bill," pieces of fruit :)")
当你创建类Bill的实例时:
purchase = Bill(5,6,7)
你得到:
> Buy 5 apples 6 figs and 7 dates. Total fruitty bill is 18 pieces of> fruit :)