Example 1: @property in python
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
print('Getting name')
return self._name
@name.setter
def name(self, value):
print('Setting name to ' + value)
self._name = value
@name.deleter
def name(self):
print('Deleting name')
del self._name
p = Person('Adam')
print('The name is:', p.name)
p.name = 'John'
del p.name
Example 2: class attributes in python
class MyClass:
# Class attributes are defined outside of constructor
class_attr = 0
def __init__(self, inst):
# Instance attributes are defined in the constructor
self.instance_attr = inst
obj = MyClass(1)
print(obj.class_attr) # outputs 0
print(obj.instance_attr) # outputs 1
print(MyClass.class_attr) # outputs 0
print(MyClass.instance_attr) # raises AttributeError
Example 3: python class
class Person:#set name of class to call it
def __init__(self, name, age):#func set ver
self.name = name#set name
self.age = age#set age
def myfunc(self):#func inside of class
print("Hello my name is " + self.name)# code that the func dose
p1 = Person("barry", 50)# setting a ver fo rthe class
p1.myfunc() #call the func and whitch ver you want it to be with
Example 4: python class
class Dog(object):
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("Hi I'm ", self.name, 'and I am', self.age, 'Years Old')
JUB0T = Dog('JUB0T', 55)
Friend = Dog('Doge', 10)
JUB0T.speak()
Friend.speak()
Example 5: @property in python
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
print('Getting name')
return self._name
def set_name(self, value):
print('Setting name to ' + value)
self._name = value
def del_name(self):
print('Deleting name')
del self._name
# Set property to use get_name, set_name
# and del_name methods
name = property(get_name, set_name, del_name, 'Name property')
p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name
Example 6: Python Class Example
#Source: https://vegibit.com/python-class-examples/
class Vehicle:
def __init__(self, brand, model, type):
self.brand = brand
self.model = model
self.type = type
self.gas_tank_size = 14
self.fuel_level = 0
def fuel_up(self):
self.fuel_level = self.gas_tank_size
print('Gas tank is now full.')
def drive(self):
print(f'The {self.model} is now driving.')
obj = Vehicle("Toyota", "Carola", "Car")
obj.drive()