Python

Python:判斷變數類型的方法

設計一個Python程式時,往往會有許多"變數物件"被宣告出來 ,這些東西可以使用type()來得到變數的物件類別,如果要辨別這個物件是否屬於某一個類別,我們可以使用isinstance()

type()

用法

type( object )  # return class information

範例

x = 0
print(type(x))   # >>> <class 'int'>
x = 0.0
print(type(x))   # >>> <class 'float'>
class car():
    pass

class audi(car):
    def a3(self):
        pass

class toyota(car):
    def yaris(self):
        pass

print(type(car))  # <class 'type'>
print(type(car()))  # <class '__main__.car'>

print(type(audi))  # <class 'type'>
print(type(audi()))  # <class '__main__.audi'>
print(type(audi().a3))  # <class 'method'>

print(type(toyota))  # <class 'type'>
print(type(toyota()))  # <class '__main__.toyota'>
print(type(toyota().yaris))  # <class 'method'>

isinstance()

用法

isinstance( object , type )
  • object:辨別的物件(object)
  • type:定義一個、多個的型態(type)或類別(class)

範例

x = 0
isinstance( x, int )  # return True
isinstance( x, float )  # return False
isinstance( x, (int, float, str) )  # return True
class car():
    pass

class bike():
    pass

obj = car()
print(isinstance(obj , car))  # return True
print(isinstance(obj , bike))  # return False

1,857 則留言

  • hdqddzkwb

    Les avis de penalty shoot out chacun d’eux recevra 1 000 € en cash, des symboles spéciaux et des multiplicateurs et vous pouvez également voir une petite boîte des 5 derniers qui montre vos 5 derniers gains. Coral propose les mêmes jeux en ligne tels que la machine à sous Age Of Discovery de Leander casino, des règles et des bonus innovants. Contactez nous : Le jeu Penalty Shoot Out Street dispose d’un mode gratuit. Il s’agit d’une version de démonstration du jeu. Vous pouvez y jouer sur les sites officiels des casinos en ligne qui proposent Penalty Shoot Out Street dans leur ludothèque. Cependant, il y a beaucoup plus de jeux amusants à essayer. Dragon Coins est une machine à sous de Revolver Gaming, penalty Shoot Out classements vous pourrez en disposer comme le voulez. Vraisemblablement, comment jouer à la machine à sou Penalty Shoot Out en ligne cliquez simplement sur s’asseoir ou rejoindre le jeu pour commencer.
    https://ptitjardin.ouvaton.org/?chillrenega1970
    🕵🏼 Can you guess the correct logo? 👍 UNLOCK FREE ADMIN AT 80% LIKES! ⭐ Your progress saves so don’t worry about losing your hard work! 💰 Support us by getting gamepasses! Your purchase goes a long way! 🔥 Join our group for exclusive rewards! 👉 roblox groups 33791966 : Guess, Logo Quiz, Exciting Race, Special Admin Access, Survival Journey, Relaxing Hangout, Scary Moments, Engaging Roleplay, Obby, Easy, Hard The the next time I read a weblog, Lets hope who’s doesnt disappoint me about that one. I am talking about, I know it was my choice to read, but I actually thought youd have something fascinating to say. All I hear is a bunch of whining about something that you could fix should you werent too busy in search of attention.

留下一個回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *