xxxxxxxxxx
#implement __enter__ and __exit__ magic methods for a object inteded to be used in a with block
MODE = 'rb'
class Meter():
def __init__(self, dev):
self.dev = dev
def __enter__(self):
#ttysetattr etc goes here before opening and returning the file object
self.fd = open(self.dev, MODE)
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
#Exception handling here
self.fd.close()
meter = Meter('/dev/tty0')
with meter as m:
#here you work with the file object.
m.fd.read()
xxxxxxxxxx
#------------------------------------
#CLASS
#------------------------------------
class Student:
def __init__(self):
self.name = None
def set_name(self, word):
self.name = word
return self.get_name()
def get_name(self):
return self.name
#------------------------------------
# USAGE:
#------------------------------------
a = Student()
print(a.set_name("Hello"))
xxxxxxxxxx
# Python program to demonstrate
# use of a class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a
# Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a
# Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print(person1.age)
print(person2.age)
# print the result
print(Person.isAdult(22))
xxxxxxxxxx
class MyClass:
my_class_variable = 42
@classmethod
def my_class_method(cls):
return cls.my_class_variable
# Accessing the class method
result = MyClass.my_class_method()
print(result)
xxxxxxxxxx
class MyClass:
def my_function(self):
# Function logic goes here
pass
def another_function(self):
# Another function defined in the class
pass