Learn Python 3 - Classes Cheatsheet - Codecademy
Learn Python 3 - Classes Cheatsheet - Codecademy
Classes
Python repr method
The Python __repr__() method is used to tell Python
what the string representation of the class should be. It class Employee:
can only have one parameter, self , and it should def __init__(self, name):
return a string.
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # John
def bark(self):
print("Ham-Ham")
charlie = Dog()
charlie.bark()
pass
# Class Instantiation
ferrari = Car()
print(x.class_variable) #I am a Class
Variable!
print(y.class_variable) #I am a Class
Variable!
dog = Animal('Woof')
print(dog.voice) # Output: Woof
a = 1.1
print(type(a)) # <class 'float'>
a = 'b'
print(type(a)) # <class 'str'>
a = None
print(type(a)) # <class 'NoneType'>
Python class
In Python, a class is a template for a data type. A class
can be defined using the class keyword. # Defining a class
class Animal:
def __init__(self, name,
number_of_legs):
self.name = name
self.number_of_legs = number_of_legs
def print_name(self):
print("Hi, I'm " + self.name)
print(dir())
# ['Employee', '__builtins__', '__doc__',
'__file__', '__name__', '__package__',
'new_employee']
print(dir(Employee))
# ['__doc__', '__init__', '__module__',
'print_name']
__main__ in Python
In Python, __main__ is an identifier used to reference
the current file context. When a module is read from
standard input, a script, or from an interactive prompt,
its __name__ is set equal to __main__ .
Suppose we create an instance of a class called
CoolClass . Printing the type() of the instance will
result in:
<class '__main__.CoolClass'>