Self made python class

Home / Uncategorized / Self made python class

Question:
I defined two class in a separated file (which name is MyClass.py) from my main program and I am trying to include it. The class definition is as follows:class MyClass:
Tn=""

def _init_(self,TN):self.Tn=TN

while my main program is as follows
import MyClass as MC

obj=MC.MyClass("hello")
print(obj.Tn)

And when I try to launch it the following message appear: "name ‘Team_class ‘is not defined". This makes me think that it doesn’t import the class correctly but I don’t seem to understand the reason.


Answer:
At first, your class’ __init__() method is wrong. I don’t know if you just copied it here wrong, but try this:class MyClass:
# __init__() is a magic method and needs two underscores, not one

def __init__(self, tn=”):# Giving a default value in your __init__() method
# is the more straightforward way of doing this

# It is also more pythonic to name your variables in snake_case

self.tn = tn

Then in your main file:import MyClass as mc

obj = mc.MyClass(‘Hello’)
print(obj.tn) # Hello

But can you show us where Team_class is used in order to resolve your error?
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *