/oop.py Secret
Created
August 3, 2021 17:56
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# !/usr/bin/python3 | |
class ClassWithMethod: | |
def say_something(self): | |
print("Elementary!") | |
class ClassWithField: | |
def __init__(self, name): | |
self.name = name | |
class ClassWithFieldAndMethod: | |
def tellName(self): | |
print(self.name) | |
class ClassWithPrivateFieldAndMethod: | |
def setName(self, name): | |
self.__name = name | |
class ClassWithParamaterInConstructor: | |
def __init__(self, name): | |
self.name = name | |
class ClassWithStaticField: | |
field = 40 | |
def someMethod(): | |
pass | |
def main(): | |
objectWithMethod = ClassWithMethod() | |
objectWithMethod.say_something() | |
objectWithField = ClassWithField("Lestrade") | |
print(objectWithField.name) | |
objectWithFieldAndMethod = ClassWithFieldAndMethod() | |
objectWithFieldAndMethod.name = "John Watson" | |
objectWithFieldAndMethod.tellName() | |
objectWithFieldAndMethod2 = ClassWithFieldAndMethod() | |
objectWithFieldAndMethod2.name = "Sherlock Holmes" | |
objectWithFieldAndMethod2.tellName() | |
# you can add field on the fly... | |
# ... to the object! | |
objectWithFieldAndMethod2.age = 33 | |
# you can do this only if field has been added: | |
print(objectWithFieldAndMethod2.age) | |
# this results in error! | |
#print(objectWithFieldAndMethod.age) | |
objectWithPrivateField = ClassWithPrivateFieldAndMethod() | |
objectWithPrivateField.setName("Mary Watson") | |
# you can not do this (error:) | |
#print(objectWithPrivateField.__name) | |
# but you can this: | |
print(objectWithPrivateField._ClassWithPrivateFieldAndMethod__name) | |
objectConstructedWithParam = ClassWithParamaterInConstructor("Moriarty") | |
print(objectConstructedWithParam.name) | |
stat1 = ClassWithStaticField() | |
stat2 = ClassWithStaticField() | |
stat2.field = 41 | |
print(stat1.field) # object's field default value is 40 | |
print(stat2.field) # this object's field value is 41 | |
print(stat1.field) # object's field default value is 40 | |
print(ClassWithStaticField.field) # static field value is still 40! | |
ClassWithStaticField.field = 42 | |
print(ClassWithStaticField.field) # not anymore! | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment